#include "test.h" #include "math.h" #include int test_a(const int value) { int result; for (int i = 0; i < 80000000; ++i) { result = value * i; } return result; } void test_b(int& value) { for (int i = 0; i < 80000000; ++i) { value *= i; } } Test::Test(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Concurrent test")); resize(800, 600); watcher1 = new QFutureWatcher(this); connect(watcher1, SIGNAL(resultReadyAt(int)), SLOT(printIndex(int))); connect(watcher1, SIGNAL(finished()), SLOT(finished())); watcher2 = new QFutureWatcher(this); connect(watcher2, SIGNAL(resultReadyAt(int)), SLOT(printIndex(int))); connect(watcher2, SIGNAL(finished()), SLOT(finished())); test1Button = new QPushButton(tr("Run test1")); connect(test1Button, SIGNAL(clicked()), SLOT(test1())); test2Button = new QPushButton(tr("Run test2")); connect(test2Button, SIGNAL(clicked()), SLOT(test2())); QHBoxLayout *buttonLayout = new QHBoxLayout(); buttonLayout->addWidget(test1Button); buttonLayout->addWidget(test2Button); buttonLayout->addStretch(); textEdit = new QTextEdit; mainLayout = new QVBoxLayout(); mainLayout->addLayout(buttonLayout); mainLayout->addWidget(textEdit, 1); setLayout(mainLayout); } Test::~Test() { watcher1->cancel(); watcher1->waitForFinished(); watcher2->cancel(); watcher2->waitForFinished(); } void Test::test1() { // Cancel and wait if we are already in test1. if (watcher1->isRunning()) { watcher1->cancel(); watcher1->waitForFinished(); } QVector vector(10, 256); textEdit->clear(); textEdit->append(tr("Test1 started.")); watcher1->setFuture(QtConcurrent::mapped(vector, test_a)); } void Test::test2() { // Cancel and wait if we are already in test2. if (watcher2->isRunning()) { watcher2->cancel(); watcher2->waitForFinished(); } QVector vector(10, 256); textEdit->clear(); textEdit->append(tr("Test2 started.")); watcher2->setFuture(QtConcurrent::map(vector, test_b)); } void Test::printIndex(int index) { textEdit->append(tr("Index finished = %0").arg(index)); } void Test::finished() { textEdit->append(tr("Test finished.")); }