void QVX_Sim::IntegrateMT(IntegrationType Integrator) { switch (Integrator){ case I_EULER: { QFuture<void> res = QtConcurrent::map(BondArray.begin(), BondArray.end(), QVX_Sim::BondCalcForce); res.waitForFinished(); ////Update Forces... //int iT = NumBond(); //for (int i=0; i<iT; i++){ // QFuture<void> future = QtConcurrent::run(BondCalcForce, &BondArray[i]); // //BondArray[i].CalcForce(); //} OptimalDt = CalcMaxDt(); dt = DtFrac*OptimalDt; res = QtConcurrent::map(VoxArray.begin(), VoxArray.end(), QVX_Sim::VoxEulerStep); res.waitForFinished(); //Update positions... need to do thises seperately if we're going to do damping in the summing forces stage. // int iT = NumVox(); // for (int i=0; i<iT; i++) VoxArray[i].EulerStep(); } break; } }
void CmdSandboxMeshLoaderFuture::activated(int iMsg) { // use current path as default QStringList filter; filter << QObject::tr("All Mesh Files (*.stl *.ast *.bms *.obj)"); filter << QObject::tr("Binary STL (*.stl)"); filter << QObject::tr("ASCII STL (*.ast)"); filter << QObject::tr("Binary Mesh (*.bms)"); filter << QObject::tr("Alias Mesh (*.obj)"); filter << QObject::tr("Inventor V2.1 ascii (*.iv)"); //filter << "Nastran (*.nas *.bdf)"; filter << QObject::tr("All Files (*.*)"); // Allow multi selection QStringList fn = Gui::FileDialog::getOpenFileNames(Gui::getMainWindow(), QObject::tr("Import mesh"), QString(), filter.join(QLatin1String(";;"))); QFuture< Base::Reference<Mesh::MeshObject> > future = QtConcurrent::mapped (fn, loadMesh); QFutureWatcher< Base::Reference<Mesh::MeshObject> > watcher; watcher.setFuture(future); // keep it responsive during computation QEventLoop loop; QObject::connect(&watcher, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); App::Document* doc = App::GetApplication().getActiveDocument(); for (QFuture< Base::Reference<Mesh::MeshObject> >::const_iterator it = future.begin(); it != future.end(); ++it) { Mesh::Feature* mesh = static_cast<Mesh::Feature*>(doc->addObject("Mesh::Feature","Mesh")); mesh->Mesh.setValuePtr((Mesh::MeshObject*)(*it)); mesh->purgeTouched(); } }
void ImageWidget::updateImage(bool zoom, const QImage &image, bool valuesPresent[], int values[]) { if(zoom) { QImage imageNew = scaleImage(image); if(imageNew.isNull()) return; #ifndef QT_NO_CONCURRENT QFuture<QImage> future = QtConcurrent::run(this, &ImageWidget::scaleImage, image); imageNew = future.result(); #else QImage imageNew = scaleImage(image); #endif pixmap = QPixmap::fromImage(imageNew); } else { pixmap = QPixmap::fromImage(image); } for(int i=0; i<4; i++) { drawValues[i] = valuesPresent[i]; if(drawValues[i]) geoValues[i] = values[i]; else geoValues[i] = 0; } update(); }
void Integration::initEgl() { Q_ASSERT(m_eglDisplay == EGL_NO_DISPLAY); // This variant uses Wayland as the EGL platform qputenv("EGL_PLATFORM", "wayland"); m_eglDisplay = eglGetDisplay(waylandServer()->internalClientConection()->display()); if (m_eglDisplay == EGL_NO_DISPLAY) { return; } // call eglInitialize in a thread to not block QFuture<bool> future = QtConcurrent::run([this] () -> bool { EGLint major, minor; if (eglInitialize(m_eglDisplay, &major, &minor) == EGL_FALSE) { return false; } EGLint error = eglGetError(); if (error != EGL_SUCCESS) { return false; } return true; }); // TODO: make this better while (!future.isFinished()) { waylandServer()->internalClientConection()->flush(); QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents); } if (!future.result()) { eglTerminate(m_eglDisplay); m_eglDisplay = EGL_NO_DISPLAY; } }
void SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd( SyntaxHighlighter *highlighter, const QFuture<HighlightingResult> &future) { // find block number of last result int lastBlockNumber = 0; for (int i = future.resultCount() - 1; i >= 0; --i) { const HighlightingResult &result = future.resultAt(i); if (result.line) { lastBlockNumber = result.line - 1; break; } } QTextDocument *doc = highlighter->document(); const int firstBlockToClear = lastBlockNumber + 1; if (firstBlockToClear <= doc->blockCount()) return; QTextBlock b = doc->findBlockByNumber(firstBlockToClear); while (b.isValid()) { QVector<QTextLayout::FormatRange> noFormats; highlighter->setExtraFormats(b, noFormats); b = b.next(); } }
void SettingsUnLinkStoreDevice::tryToDisassociate() { qDebug() << "--->" << Q_FUNC_INFO; disconnectWifiObserverUnlinkBtn(); Screen::getInstance()->queueUpdates(); SelectionDialog* confirmDialog = new SelectionDialog(this,tr("Do you want to unlink the device? This will delete all your personal account data")); Screen::getInstance()->setMode(Screen::MODE_SAFE,true, FLAG_FULLSCREEN_UPDATE,Q_FUNC_INFO); Screen::getInstance()->setUpdateScheme(Screen::SCHEME_MERGE, true); Screen::getInstance()->flushUpdates(); confirmDialog->exec(); bool result = confirmDialog->result(); delete confirmDialog; if(!result) return; disconnect(Storage::getInstance(), SIGNAL(partitionMounted(StoragePartition*)), QBookApp::instance(), SLOT(handlePartitionMounted(StoragePartition*))); PowerManagerLock* powerLock = PowerManager::getNewLock(this); powerLock->activate(); QBookApp::instance()->cancelSync(); //Screen::getInstance()->queueUpdates(); InfoDialog *dialog = new InfoDialog(this,tr("This process can take a few minutes. At the end, the device will be powered off")); dialog->show(); Screen::getInstance()->setMode(Screen::MODE_SAFE,true, FLAG_FULLSCREEN_UPDATE,Q_FUNC_INFO); //Screen::getInstance()->setUpdateScheme(Screen::SCHEME_MERGE, true); //Screen::getInstance()->flushUpdates(); #ifndef HACKERS_EDITION bqDeviceServices* services = QBookApp::instance()->getDeviceServices(); services->unlink(); #endif if (true) { QBookApp::instance()->disableUserEvents(); QBookApp::instance()->getSyncHelper()->SetServerTimestamp(0); QBookApp::instance()->syncModel(); QBookApp::instance()->showRestoringImage(); Screen::getInstance()->queueUpdates(); // Remove private books from model QBookApp::instance()->getModel()->removeDir(Storage::getInstance()->getPrivatePartition()->getMountPoint()); QFuture<void> future = QtConcurrent::run(this, &SettingsUnLinkStoreDevice::restoreSettinsAndPartitions, dialog); if (!future.isFinished()) dialog->exec(); Screen::getInstance()->setMode(Screen::MODE_SAFE, true, FLAG_FULLSCREEN_UPDATE, Q_FUNC_INFO); PowerManager::powerOffDevice(true); } else { InfoDialog *unlinkFailedDialog = new InfoDialog(this,tr("Service unavailable. Please try again in a few minutes")); Screen::getInstance()->setMode(Screen::MODE_SAFE,true,Q_FUNC_INFO); unlinkFailedDialog->hideSpinner(); unlinkFailedDialog->showForSpecifiedTime(); delete unlinkFailedDialog; powerLock->release(); delete powerLock; } }
void MeshCurvature::ComputePerFace(bool parallel) { Base::Vector3f rkDir0, rkDir1, rkPnt; Base::Vector3f rkNormal; myCurvature.clear(); MeshRefPointToFacets search(myKernel); FacetCurvature face(myKernel, search, myRadius, myMinPoints); if (!parallel) { Base::SequencerLauncher seq("Curvature estimation", mySegment.size()); for (std::vector<unsigned long>::iterator it = mySegment.begin(); it != mySegment.end(); ++it) { CurvatureInfo info = face.Compute(*it); myCurvature.push_back(info); seq.next(); } } else { QFuture<CurvatureInfo> future = QtConcurrent::mapped (mySegment, boost::bind(&FacetCurvature::Compute, &face, _1)); QFutureWatcher<CurvatureInfo> watcher; watcher.setFuture(future); watcher.waitForFinished(); for (QFuture<CurvatureInfo>::const_iterator it = future.begin(); it != future.end(); ++it) { myCurvature.push_back(*it); } } }
void PlayListImageThumbnailHistogramGrouper::group(ImageList::iterator begin, ImageList::iterator end) { std::vector<QSharedPointer<ImageHistogram> > hists; // Load thumbnail and compute thumbnail histograms QFuture<QSharedPointer<ImageHistogram> > f = QtConcurrent::mapped(begin, end, computeImageHistogram); f.waitForFinished(); for (QSharedPointer<ImageHistogram> hist : f) { hists.push_back(hist); } // Partition std::vector<int> labels; int groupCount = cv::partition(hists, labels, isHistSame); m_groupNames.clear(); for (int i = 0; i < groupCount; i++) { m_groupNames << QStringLiteral("Group %1").arg(i); } for (auto it = begin; it != end; it++) { m_imageGroups[it->data()] = labels[it - begin]; } // Sort by group std::sort(begin, end, [this](const ImagePtr &left, const ImagePtr &right) -> bool { int leftLabel = this->m_imageGroups[left.data()]; int rightLabel = this->m_imageGroups[right.data()]; if (leftLabel != rightLabel) { return leftLabel < rightLabel; } else { return ImageNameLessThan(left->name(), right->name()); } }); }
void DocsetRegistry::_runQuery(const QString &query) { m_cancellationToken.reset(); QList<Docset *> enabledDocsets; const SearchQuery searchQuery = SearchQuery::fromString(query); if (searchQuery.hasKeywords()) { for (Docset *docset : qAsConst(m_docsets)) { if (searchQuery.hasKeywords(docset->keywords())) enabledDocsets << docset; } } else { enabledDocsets = docsets(); } QFuture<QList<SearchResult>> queryResultsFuture = QtConcurrent::mappedReduced(enabledDocsets, std::bind(&Docset::search, std::placeholders::_1, searchQuery.query(), std::ref(m_cancellationToken)), &MergeQueryResults); QList<SearchResult> results = queryResultsFuture.result(); if (m_cancellationToken.isCanceled()) return; std::sort(results.begin(), results.end()); if (m_cancellationToken.isCanceled()) return; emit searchCompleted(results); }
QNetworkReply::NetworkError NetworkServiceAccessor::get(const QNetworkRequest &request, QByteArray &replyData, QList<QNetworkReply::RawHeaderPair> &headers) const { QNetworkReply::NetworkError result = QNetworkReply::NoError; QFuture<void> future = QtConcurrent::run(QThreadPool::globalInstance(), [&](){ QEventLoop loop; QNetworkAccessManager networkAccessManager; QNetworkReply *reply = networkAccessManager.get(request); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); LoggingManager::getSingleton().log() << "NetworkService Get: " << request.url().toString(); qDebug() << "NetworkService Get:" << request.url().toString(); loop.exec(); result = reply->error(); if (result != QNetworkReply::NoError) { qDebug() << "Network Service Accessor Error: " << reply->errorString(); qDebug() << "error code:" << reply->error(); LoggingManager::getSingleton().log() << "NetworkService: " << reply->errorString(); } headers = reply->rawHeaderPairs(); replyData = reply->readAll(); qDebug() << replyData; reply->deleteLater();}); future.waitForFinished(); return result; }
QNetworkReply::NetworkError NetworkServiceAccessor::post(const QNetworkRequest &request, const QByteArray &data, QByteArray &replyData) const { QNetworkReply::NetworkError result = QNetworkReply::NoError; QFuture<void> future = QtConcurrent::run(QThreadPool::globalInstance(), [&](){ QEventLoop loop; QNetworkAccessManager networkAccessManager; QNetworkReply *reply = networkAccessManager.post(request, data); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); LoggingManager::getSingleton().log() << "NetworkService Post: " << request.url().toString(); qDebug() << "NetworkService Post: " << request.url().toString(); LoggingManager::getSingleton().log() << "Payload: " << QString::fromUtf8(data); qDebug() << "Payload: " << QString::fromUtf8(data); loop.exec(); result = reply->error(); if (result != QNetworkReply::NoError) { qDebug() << "Network Service Accessor Error: " << reply->errorString(); LoggingManager::getSingleton().log() << "NetworkService: " << reply->errorString(); } replyData = reply->readAll(); qDebug() << replyData; reply->deleteLater(); }); future.waitForFinished(); return result; }
void auto_expand_image::run() { //qRegisterMetaType<QPainterPath >("QPainterPath"); //! =============== begin running_text_left+=running_text_left_add;//滚动字幕 if(running_text_left>=image_width)running_text_left=-running_text.textWidth(); percent_finish=1.0*(image_running_step%image_running_step_total)/(image_running_step_total-1); if(image_running_step%image_running_step_total==0){ image_switch_step++; //获取上一个图片的path if(draw_pixmap_paths.count() > 0) draw_pixmap_path_pre=draw_pixmap_paths[(image_switch_step-1)%draw_pixmap_paths.count()]; } //当前绘制的pixmap draw_pixmap_path_cur=draw_pixmap_paths[image_switch_step%draw_pixmap_paths.count()]; image_running_step++;//图片切换 //! =============== end QFuture<void> future = QtConcurrent::run(POP_INTERVAL_IMAGE, this, paint_rotate, percent_finish, polygon_vect, draw_pixmap_path_cur ); future.waitForFinished(); }
CC_FILE_ERROR BinFilter::loadFile(const char* filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, double* coordinatesShift/*=0*/) { ccLog::Print("[BIN] Opening file '%s'...",filename); //opening file QFile in(filename); if (!in.open(QIODevice::ReadOnly)) return CC_FERR_READING; uint32_t firstBytes = 0; if (in.read((char*)&firstBytes,4)<0) return CC_FERR_READING; bool v1 = (strncmp((char*)&firstBytes,"CCB2",4) != 0); if (v1) { return LoadFileV1(in,container,static_cast<unsigned>(firstBytes),alwaysDisplayLoadDialog); //firstBytes == number of scans for V1 files! } else { if (alwaysDisplayLoadDialog) { QProgressDialog pDlg(QString("Loading: %1").arg(QFileInfo(filename).fileName()),QString(),0,0/*static_cast<int>(in.size())*/); pDlg.setWindowTitle("BIN file"); pDlg.show(); //concurrent call in a separate thread s_file = ∈ s_container = &container; QFuture<CC_FILE_ERROR> future = QtConcurrent::run(_LoadFileV2); while (!future.isFinished()) { #if defined(CC_WINDOWS) ::Sleep(500); #else usleep(500 * 1000); #endif if (alwaysDisplayLoadDialog) { pDlg.setValue(pDlg.value()+1); //pDlg.setValue(static_cast<int>(in.pos())); //DGM: in fact, the file reading part is just half of the work! QApplication::processEvents(); } } s_file = 0; s_container = 0; return future.result(); } else { return BinFilter::LoadFileV2(in,container); } } }
void TestRunFunction::runHeavyFunction() { qDebug("starting function"); QFuture<void> future = run(F(heavy)); qDebug("waiting"); future.waitForFinished(); qDebug("done"); }
void tst_QtConcurrentRun::runLightFunction() { qDebug("starting function"); QFuture<void> future = run(F(light)); qDebug("waiting"); future.waitForFinished(); qDebug("done"); }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QFuture<void> future = QtConcurrent::run(hello); qDebug() << "hello from GUI thread " << QThread::currentThread(); future.waitForFinished(); return 0; }
bool QThreadFutureMap::isAlive(const QString &id) { QFuture<void> *future = getFuture(id); if (future != NULL) { return !future->isFinished(); } return false; }
void tst_QtConcurrentRun::runHeavyFunction() { QThreadPool pool; qDebug("starting function"); QFuture<void> future = run(&pool, heavy); qDebug("waiting"); future.waitForFinished(); qDebug("done"); }
void tst_QtConcurrentIterateKernel::multipleResults() { QFuture<int> f = startThreadEngine(new MultipleResultsFor(0, 10)).startAsynchronously(); QCOMPARE(f.results().count() , 10); QCOMPARE(f.resultAt(0), 0); QCOMPARE(f.resultAt(5), 5); QCOMPARE(f.resultAt(9), 9); f.waitForFinished(); }
QList<LocatorFilterEntry> BasicLocatorFilterTest::matchesFor(const QString &searchText) { doBeforeLocatorRun(); const QList<ILocatorFilter *> filters = QList<ILocatorFilter *>() << m_filter; QFuture<LocatorFilterEntry> locatorSearch = QtConcurrent::run(Core::Internal::runSearch, filters, searchText); locatorSearch.waitForFinished(); doAfterLocatorRun(); return locatorSearch.results(); }
void tst_QtConcurrentThreadEngine::multipleResults() { MultipleResultsUser *engine = new MultipleResultsUser(); QFuture<int> f = engine->startAsynchronously(); QCOMPARE(f.results().count() , 10); QCOMPARE(f.resultAt(0), 0); QCOMPARE(f.resultAt(5), 5); QCOMPARE(f.resultAt(9), 9); f.waitForFinished(); }
void tst_iteratekernel::cancel() { { QFuture<void> f = startThreadEngine(new SleepPrintFor(0, 40)).startAsynchronously(); f.cancel(); f.waitForFinished(); QVERIFY(f.isCanceled()); QVERIFY(int(iterations) <= QThread::idealThreadCount()); // the threads might run one iteration each before they are canceled. } }
bool CatalogConnector::loadDataThreaded(IlwisObject *obj, const IOOptions &options){ kernel()->issues()->log(QString(TR("Scanning %1")).arg(source().url(true).toString()),IssueObject::itMessage); QVector<std::pair<CatalogExplorer *, IOOptions>> explorers; for(const auto& explorer : _dataProviders){ explorers.push_back({explorer.get(), options}); } QFuture<std::vector<Resource>> res = QtConcurrent::mappedReduced(explorers,loadExplorerData, gatherData); res.waitForFinished(); mastercatalog()->addItems(res.result()); return true; }
void RunConcurrentMapExample() { QStringList strings; strings << "foo" << "bar" << "baz"; QFuture<void> res = QtConcurrent::map(strings,UpcaseString()); res.waitForFinished(); for(QStringList::iterator i = strings.begin(); i != strings.end(); ++i) qDebug("%s",qPrintable(*i)); }
QList<LocatorFilterEntry> BasicLocatorFilterTest::matchesFor(const QString &searchText) { doBeforeLocatorRun(); const QList<ILocatorFilter *> filters = QList<ILocatorFilter *>() << m_filter; m_filter->prepareSearch(searchText); QFuture<LocatorFilterEntry> locatorSearch = Utils::runAsync(&Internal::runSearch, filters, searchText); locatorSearch.waitForFinished(); doAfterLocatorRun(); return locatorSearch.results(); }
void tst_QFuture::progressText() { QFutureInterface<void> i; i.reportStarted(); QFuture<void> f = i.future(); QCOMPARE(f.progressText(), QLatin1String("")); i.setProgressValueAndText(1, QLatin1String("foo")); QCOMPARE(f.progressText(), QLatin1String("foo")); i.reportFinished(); }
void tst_QtConcurrentIterateKernel::cancel() { { QFuture<void> f = startThreadEngine(new SleepPrintFor(0, 40)).startAsynchronously(); f.cancel(); f.waitForFinished(); QVERIFY(f.isCanceled()); // the threads might run one iteration each before they are canceled. QVERIFY2(iterations.load() <= QThread::idealThreadCount(), (QByteArray::number(iterations.load()) + ' ' + QByteArray::number(QThread::idealThreadCount()))); } }
int BaseFilter::start() { if (s_computing) { throwError(-32); return -1; } QProgressDialog progressCb("Operation in progress",QString(),0,0); if (m_show_progress) { progressCb.setWindowTitle(getFilterName()); progressCb.show(); QApplication::processEvents(); } s_computeStatus = -1; s_filter = this; s_computing = true; int progress = 0; QFuture<void> future = QtConcurrent::run(doCompute); while (!future.isFinished()) { #if defined(CC_WINDOWS) ::Sleep(500); #else usleep(500 * 1000); #endif if (m_show_progress) progressCb.setValue(++progress); } int is_ok = s_computeStatus; s_filter = 0; s_computing = false; if (m_show_progress) { progressCb.close(); QApplication::processEvents(); } if (is_ok < 0) { throwError(is_ok); return -1; } return 1; }
void windowLoadMiRNAF::on_buttonChooseMirnaF_clicked() { fileNameMiRNA=QFileDialog::getOpenFileName( this, tr("Choose File"), "", "FASTA files (*.fasta);;Text files (*.txt);;All files (*)" ); if(!fileNameMiRNA.isEmpty()){ ui->progressBar->show(); try { QFuture<bool> future = QtConcurrent::run(&QtExceptionWrapper::targetFinder_getMiRNAs,m_oTF,fileNameMiRNA.toStdString()); //m_oTF->getMiRNAs(fileNameMiRNA.toStdString()); this->FutureWatcher.setFuture(future); future.result(); //make visible labelFileSelectedMirna ui->labelFileSelectedMirna->setVisible(true); //change the value of labelFileSelectedMirna ui->labelFileSelectedMirna->setText(tr("Mirna File selected : ")+fileNameMiRNA); //make the button next accessible ui->NextAnalyzeResults->setEnabled(true); this->ui->progressBar->setMaximum(100); this->ui->progressBar->setValue(100); }catch(MyException const& e) { QMessageBox::warning(this,tr("Loading error"),e.what()); //hiding labelFileSelectedMirna ui->labelFileSelectedMirna->setVisible(false); //change the value of labelFileSelectedMirna ui->labelFileSelectedMirna->setText(tr("")); //make the button next disabled ui->NextAnalyzeResults->setEnabled(false); this->ui->progressBar->hide(); }catch(std::string const& e2) { QMessageBox::warning(this,tr("Loading error"),QString::fromStdString(e2)); //hiding labelFileSelectedMirna ui->labelFileSelectedMirna->setVisible(false); //change the value of labelFileSelectedMirna ui->labelFileSelectedMirna->setText(tr("")); //make the button next disabled ui->NextAnalyzeResults->setEnabled(false); this->ui->progressBar->hide(); } } else{ QMessageBox::warning(this,tr("File selected"),tr("No file selected")); } }
void tst_QtConcurrentThreadEngine::runDirectly() { { PrintUser engine; engine.startSingleThreaded(); engine.startBlocking(); } { PrintUser *engine = new PrintUser(); QFuture<void> f = engine->startAsynchronously(); f.waitForFinished(); } }