Exemplo n.º 1
1
int main(int argc, char *argv[])
{
	QCoreApplication app(argc, argv);

	Worker worker;
	worker.setAutoDelete(false);

	QThreadPool *threadPool = QThreadPool::globalInstance();
	threadPool->start(&worker);

	qDebug() << "Hello from GUI thread. ID is " << (int)QThread::currentThreadId();

	threadPool->waitForDone();

	return 0;
}
Exemplo n.º 2
0
void tst_QThreadPool::waitForDoneTimeout()
{
    class BlockedTask : public QRunnable
    {
    public:
      QMutex mutex;
      BlockedTask() { setAutoDelete(false); }
      
      void run()
        {
          mutex.lock();
          mutex.unlock();
          QTest::qSleep(50);
        }
    };

    QThreadPool threadPool;

    BlockedTask *task = new BlockedTask;
    task->mutex.lock();
    threadPool.start(task);
    QVERIFY(!threadPool.waitForDone(100));
    task->mutex.unlock();
    QVERIFY(threadPool.waitForDone(400));
}
Exemplo n.º 3
0
void tst_QThreadPool::waitForDone()
{
    QTime total, pass;
    total.start();

    QThreadPool threadPool;
    while (total.elapsed() < 10000) {
        int runs;
        count.store(runs = 0);
        pass.restart();
        while (pass.elapsed() < 100) {
            threadPool.start(new CountingRunnable());
            ++runs;
        }
        threadPool.waitForDone();
        QCOMPARE(count.load(), runs);

        count.store(runs = 0);
        pass.restart();
        while (pass.elapsed() < 100) {
            threadPool.start(new CountingRunnable());
            threadPool.start(new CountingRunnable());
            runs += 2;
        }
        threadPool.waitForDone();
        QCOMPARE(count.load(), runs);
    }
}
void GDALGeometricAttributes::run()
{

	//return;
	if (useSQL) {
		//run_sql();
		run_sql_threaded();
		return;
	}

	OGRFeature * f;

	vc.resetReading();
	QThreadPool pool;
	std::vector<OGRFeature*> container;
	int counter = 0;
	while( f = vc.getNextFeature() ) {
		container.push_back(f);
		if (counter%10000 == 0){
			GeometricAttributeWorker * gw = new GeometricAttributeWorker(this, container, isCalculateArea, isAspectRationBB , isPercentageFilled);
			pool.start(gw);
			container = std::vector<OGRFeature*>();
		}
	}
	pool.waitForDone();
}
Exemplo n.º 5
0
float ClusteringCoefficient::Compute() {
    QList<FeaturesComplexNetwork::Node> ids;
    ids.reserve(cn.getNumNodes());
    for(FeaturesComplexNetwork::NodeIt it(cn); it != INVALID; ++it){
        ids.append( it );
    }
    std::random_shuffle(ids.begin(), ids.end());

    QList<QList<FeaturesComplexNetwork::Node>> lists;
    lists.append(QList<FeaturesComplexNetwork::Node>());

    int j=0;
    for(int i=0;i< ids.size()*ratio; i++){
        lists.last().append(ids[i]);
        j++;
        if( j > 50 ){
            j=0;
            lists.append(QList<FeaturesComplexNetwork::Node>());
        }
    }


    FeaturesComplexNetwork::ArcMap<double> weights(cn);
    GraphUtilities::getWeights(cn, weights);
    GraphUtilities::normalizeWeights(cn,weights,weights);

    QThreadPool pool;
    pool.setMaxThreadCount(this->threads);
    for(auto &list : lists) {
        pool.start(new ClusteringCoefficientTask(this, cn, weights, list));
    }
    pool.waitForDone();

    return std::accumulate(ccs.begin(),ccs.end(),0.f, [](const float &a, const ClusteringCoefficient::NodeCC &b){return a+b.cc;})/ccs.size();
}
Exemplo n.º 6
0
void tst_QThreadPool::tryStart()
{
    class WaitingTask : public QRunnable
    {
    public:
        QSemaphore semaphore;

        WaitingTask() { setAutoDelete(false); }

        void run()
        {
            semaphore.acquire();
            count.ref();
        }
    };

    count.store(0);

    WaitingTask task;
    QThreadPool threadPool;
    for (int i = 0; i < threadPool.maxThreadCount(); ++i) {
        threadPool.start(&task);
    }
    QVERIFY(!threadPool.tryStart(&task));
    task.semaphore.release(threadPool.maxThreadCount());
    threadPool.waitForDone();
    QCOMPARE(count.load(), threadPool.maxThreadCount());
}
Exemplo n.º 7
0
QLandmarkManagerEngineSqlite::~QLandmarkManagerEngineSqlite()
{
    QThreadPool *threadPool = QThreadPool::globalInstance();
    threadPool->waitForDone();

    if (m_dbWatcher !=0)
        delete m_dbWatcher;

    QSqlDatabase::database(m_dbConnectionName).close();
    QSqlDatabase::removeDatabase(m_dbConnectionName);
}
//! Helper function that initiates the image processing algorithms.
void MRIOpenCV::RunProcess()
{

QThreadPool *threadPool = QThreadPool::globalInstance();
for(int i=0; i < this->Processes->size(); i++){
	cout <<  this->Processes->size();
	MRIProcess * process= this->Processes->front();
	this->Processes->pop();
	process->run();
//threadPool->start(process);
	}
threadPool->waitForDone();
}
Exemplo n.º 9
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Work work;
    work.setAutoDelete(false);
    QThreadPool *threadPool = QThreadPool::globalInstance();
    threadPool->start(&work);
    qDebug() << "hello from GUI thread " << QThread::currentThread();
    threadPool->waitForDone();
}
Exemplo n.º 10
0
void KisMemoryPoolTest::benchmarkAlloc()
{
    QThreadPool pool;
    pool.setMaxThreadCount(NUM_THREADS);

    QBENCHMARK {
        for(qint32 i = 0; i < NUM_THREADS; i++) {
            KisAllocStressJob *job = new KisAllocStressJob();
            pool.start(job);
        }

        pool.waitForDone();
    }
}
Exemplo n.º 11
0
void FavIconTest::concurrentRequestsShouldWork()
{
    const int numThreads = 3;
    QThreadPool tp;
    tp.setMaxThreadCount(numThreads);
    QVector<QFuture<QString>> futures(numThreads);
    for (int i = 0; i < numThreads; ++i) {
        futures[i] = QtConcurrent::run(&tp, getAltIconUrl);
    }
    QVERIFY(tp.waitForDone(60000));

    const QString firstResult = futures.at(0).result();
    for (int i = 1; i < numThreads; ++i) {
        QCOMPARE(futures.at(i).result(), firstResult);
    }
    QVERIFY(!QPixmap(firstResult).isNull());
}
Exemplo n.º 12
0
void GDALParcelSplit::run()
{
	cityblocks.resetReading();
	OGRFeature *poFeature;
	this->counter_added = 0;

	QThreadPool pool;
	while( (poFeature = cityblocks.getNextFeature()) != NULL ) {
		char* geo;

		poFeature->GetGeometryRef()->exportToWkt(&geo); //Geo destroyed by worker
		ParcelSplitWorker * ps = new ParcelSplitWorker(poFeature->GetFID(), this, this->width, this->target_length, this->splitFirst, geo);
		pool.start(ps);
	}
	pool.waitForDone();
	this->generated = counter_added;
}
Exemplo n.º 13
0
void ConvolutionFilter::process(const QList<float> &matrix, int radius) {

	QThreadPool threadPool;
	threadPool.setMaxThreadCount(16);
	int height = image.height();

	for (int y = 0; y < height; y++) {
		ConvolutionFilterRunner *runner = new ConvolutionFilterRunner(&image);
		runner->setMatrix(matrix, radius);
		runner->setScanLine((QRgb *) processed.scanLine(y), y);
		runner->setAutoDelete(true);

		threadPool.start(runner);
	}

	printf("waiting for convolution filter...");
	threadPool.waitForDone();
}
Exemplo n.º 14
0
void tst_QPointer::threadSafety()
{

    QThread owner;
    owner.start();

    QThreadPool pool;
    for (int i = 0; i < 300; i++) {
        QPointer<TestRunnable> task = new TestRunnable;
        task->setAutoDelete(true);
        task->moveToThread(&owner);
        pool.start(task);
    }
    pool.waitForDone();

    owner.quit();
    owner.wait();
}
Exemplo n.º 15
0
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    PayLoad *payLoad = new PayLoad(QCoreApplication::arguments());

    QThreadPool *qThreadPool = QThreadPool::globalInstance();
    qThreadPool->setMaxThreadCount(payLoad->getThreads());

    if(payLoad->verify()) {
        for(int i = 0; i < payLoad->getThreads(); i++){
            qThreadPool->start(new RequestThread(i, payLoad));
        }
        qDebug() << "All threads started ..";
    } else {
        qDebug() <<"Parameters missing";
    }

    qThreadPool->waitForDone();

    qDebug() << "Done";

    return a.exec();
}
Exemplo n.º 16
0
void KisLowMemoryTests::readWriteOnSharedTiles()
{
    quint8 defaultPixel = 0;
    KisTiledDataManager srcDM(1, &defaultPixel);
    KisTiledDataManager dstDM(1, &defaultPixel);

    const int NUM_TILES = 10;
    const int NUM_CYCLES = 10000;

    QThreadPool pool;
    pool.setMaxThreadCount(10);

    pool.start(new DeadlockyThread(DeadlockyThread::PRODUCER,
                                   srcDM, dstDM, NUM_TILES, NUM_CYCLES));

    for (int i = 0; i < 4; i++) {
        pool.start(new DeadlockyThread(DeadlockyThread::CONSUMER_SRC,
                                       srcDM, dstDM, NUM_TILES, NUM_CYCLES));
        pool.start(new DeadlockyThread(DeadlockyThread::CONSUMER_DST,
                                       srcDM, dstDM, NUM_TILES, NUM_CYCLES));
    }

    pool.waitForDone();
}
Exemplo n.º 17
0
void FileAnalyzer::run()
{
	m_abortFlag = false;

	m_bAborted = false;
	m_bSuccess = false;

	int nFiles = m_inputFiles.count();

	emit progressMaxChanged(nFiles);
	emit progressValChanged(0);

	lamexp_natural_string_sort(m_inputFiles, true); //.sort();

	if(!m_templateFile)
	{
		if(!createTemplate())
		{
			qWarning("Failed to create template file!");
			return;
		}
	}

	AnalyzeTask::reset();
	QThreadPool *pool = new QThreadPool();
	QThread::msleep(333);

	pool->setMaxThreadCount(qBound(2, ((QThread::idealThreadCount() * 3) / 2), 12));

	while(!(m_inputFiles.isEmpty() || m_bAborted))
	{
		while(!(m_inputFiles.isEmpty() || m_bAborted))
		{
			if(!AnalyzeTask::waitForFreeSlot(&m_abortFlag))
			{
				qWarning("Timeout in AnalyzeTask::waitForFreeSlot() !!!");
			}

			if(m_abortFlag)
			{
				MessageBeep(MB_ICONERROR);
				m_bAborted = true;
				break;
			}
			
			if(!m_bAborted)
			{
				const QString currentFile = QDir::fromNativeSeparators(m_inputFiles.takeFirst());

				AnalyzeTask *task = new AnalyzeTask(currentFile, m_templateFile->filePath(), &m_abortFlag);
				connect(task, SIGNAL(fileSelected(QString)), this, SIGNAL(fileSelected(QString)), Qt::DirectConnection);
				connect(task, SIGNAL(progressValChanged(unsigned int)), this, SIGNAL(progressValChanged(unsigned int)), Qt::DirectConnection);
				connect(task, SIGNAL(progressMaxChanged(unsigned int)), this, SIGNAL(progressMaxChanged(unsigned int)), Qt::DirectConnection);
				connect(task, SIGNAL(fileAnalyzed(AudioFileModel)), this, SIGNAL(fileAnalyzed(AudioFileModel)), Qt::DirectConnection);

				pool->start(task);

				if(int count = AnalyzeTask::getAdditionalFiles(m_inputFiles))
				{
					emit progressMaxChanged(nFiles += count);
				}
			}
		}

		//One of the Analyze tasks may have gathered additional files from a playlist!
		if(!m_bAborted)
		{
			pool->waitForDone();
			if(int count = AnalyzeTask::getAdditionalFiles(m_inputFiles))
			{
				emit progressMaxChanged(nFiles += count);
			}
		}
	}
	
	pool->waitForDone();
	LAMEXP_DELETE(pool);

	if(m_bAborted)
	{
		qWarning("Operation cancelled by user!");
		return;
	}
	
	qDebug("All files added.\n");
	m_bSuccess = true;
}
Exemplo n.º 18
0
    void Finish()
    {
#if PARALLEL_POLYGONIZER
        m_ThreadPool.waitForDone();
#endif
    }
Exemplo n.º 19
0
void PulsarProcess::run() {
    if (!data.isValid()) {
        qDebug() << "No valid data available";
        return;
    }

    QVector<PulsarWorker*> workers;
    QThreadPool *pool = CalculationPool::pool();
    qDebug() << "splitting to" << pool->maxThreadCount() << "processes";

    if (!Settings::settings()->preciseSearch()) {
        for (int D = 0; D < 200; D += 6)
            for (int i = 0; i < data.modules; i++)
                for (int j = 0; j < data.rays; j++) {
                        workers.push_back(new PulsarWorker(i, j, D, data));
                        workers[workers.size() - 1]->setAutoDelete(false);
                        pool->start(workers[workers.size() - 1]);
                    }
    } else if (Settings::settings()->periodTester()) {
        workers.push_back(new PulsarWorker(Settings::settings()->module(), Settings::settings()->ray(), Settings::settings()->dispersion(), data));
        workers[0]->setAutoDelete(false);
        pool->start(workers[0]);
    } else {
        int mx = 200;
        if (Settings::settings()->dispersion() > -0.5)
            mx = Settings::settings()->dispersion() + 6;

        int step = 1;
        if (data.oneStep > 0.05)
            step = 3;

        for (double D = max(Settings::settings()->dispersion() - 6, 0.0); D < mx; D += step) {
            workers.push_back(new PulsarWorker(Settings::settings()->module(), Settings::settings()->ray(), D, data));
            workers[workers.size() - 1]->setAutoDelete(false);
            pool->start(workers[workers.size() - 1]);
        }

    }

    while (!pool->waitForDone(30000)) {
        bool finished = true;
        for (int i = 0; i < workers.size(); i++)
            finished &= workers[i]->finished;

        if (finished)
            break;
    }

    QVector<Pulsar> pulsars;
    for (int i = 0; i < workers.size(); i++) {
        for (int j = 0; j < workers[i]->res.size(); j++)
            pulsars.push_back(workers[i]->res[j]);

//        workers[i]->deleteLater();
    }

    qDebug() << "workers deleted";

    for (int i = 0; i < pulsars.size(); i++)
        for (int j = i + 1; j < pulsars.size(); j++)
            if ((pulsars[i].filtered && !pulsars[j].filtered) || ((pulsars[i].filtered == pulsars[j].filtered)
                                                                  && (pulsars[i].firstPoint > pulsars[j].firstPoint))) {
                Pulsar p = pulsars[i];
                pulsars[i] = pulsars[j];
                pulsars[j] = p;
            }

    QByteArray header = QString("file: %1\ntresolution %2\nStart time\tmodule\tray\tdispersion\tperiod\tsnr\tfirst_point\n").arg(data.name).arg(data.oneStep).toUtf8();

    QFile *files[CATEGORIES];
    bool filtered[CATEGORIES];
    for (int i = 0; i < CATEGORIES; i++)
        filtered[i] = false;

    QDir().mkdir(savePath);
    for (int i = 0; i < CATEGORIES; i++) {
        files[i] = new QFile(savePath + QString("%1-%2-%3.pulsar").arg(data.name).arg(CATEGORIES_SIZES[i]).arg(CATEGORIES_SIZES[i + 1]));
        files[i]->open(QIODevice::WriteOnly);
        files[i]->write(header);
    }

    for (int i = 0; i < pulsars.size(); i++)
        for (int j = CATEGORIES - 1; j >= 0; j--)
            if (CATEGORIES_SIZES[j] < pulsars[i].snr || j == 0) {
                if (!filtered[j] && pulsars[i].filtered) {
                    filtered[j] = true;
                    files[j]->write(QByteArray("filtered next\n"));
                }

                QByteArray d = QString("%1\t%2\t%3\t%4\t%5\t%6\t%7\n").
                        arg(pulsars[i].time()).
                        arg(pulsars[i].module + 1).
                        arg(pulsars[i].ray + 1).
                        arg(pulsars[i].dispersion).
                        arg(QString::number(pulsars[i].period, 'f', 5)).
                        arg(QString::number(pulsars[i].snr, 'f', 1)).
                        arg(QString::number(pulsars[i].firstPoint)).
                        toUtf8();

                files[j]->write(d);
                break;
            }

    for (int i = 0; i < CATEGORIES; i++)
        files[i]->write("additional data:\n");

    for (int i = 0; i < pulsars.size(); i++)
        for (int j = CATEGORIES - 1; j >= 0; j--)
            if (CATEGORIES_SIZES[j] < pulsars[i].snr || j == 0) {
                files[j]->write(pulsars[i].additionalData);
                break;
            }

    for (int i = 0; i < CATEGORIES; i++) {
        files[i]->close();
        delete files[i];
    }

    qDebug() << "files deleted";
}
Exemplo n.º 20
0
int main(int argc, char **argv) {

	MRIOpenCVSettings * config = new MRIOpenCVSettings();
	config->LoadSettings(
			"/home/michaelroberts/Build/MriSegment/src/Conf/MRIOpenCV/Default.conf");

	MRIOpenCV * OpencvProcessor = new MRIOpenCV();

	QApplication app(argc, argv);
	QStringList nameFilter("*.dcm");
	QDir directory(
			  QString::fromAscii(config->GetSettings("Imagesets","tdcubefat","")));
	QStringList files = directory.entryList(nameFilter);
	for (int i = 0; i < files.count(); i++)
		files[i] =
				QString(
						  QString::fromAscii(config->GetSettings("Imagesets","tdcubefat","")))
						+ files[i];

	QDir dir(
			QString::fromAscii(config->GetSettings("Imagesets","tdcubewater","")));
	QStringList filesfat = dir.entryList(nameFilter);
	for (int i = 0; i < filesfat.count(); i++)
		filesfat[i] =
				QString(
						QString::fromAscii(config->GetSettings("Imagesets","tdcubewater","")))
						+ filesfat[i];

	MRICommon * fat = new MRICommon();
	fat->LoadImages(&files);
	fat->Data->ToTransversal();
	//fat->Data->ToCorronial();

	MRICommon * water = new MRICommon();
	water->LoadImages(&filesfat);

	vector<MRICommon *> Imagesets(2);
	Imagesets.at(FATCUBE) = fat;
	Imagesets.at(WATERCUBE) = water;
	vector<LabeledResults *> results(400);

	results.at(FEMER_SAG) = new LabeledResults();
	///blur( img, img, Size(3,3) );
	QThreadPool *threadPool = QThreadPool::globalInstance();

	for (int i = 0; i < fat->Data->Sagittal->size(); i++) {
		cout << "processing image: " << i << "\n";
		FindBoneFemer * process = new FindBoneFemer(&Imagesets, &results, i,
				config);
		process->Setup();
		process->Preprocess();
		process->Segment();
		process->PostSegmentProcess();
		process->PostProcess();

	}
	threadPool->waitForDone();

	pcl::PointCloud<pcl::PointXYZ>::Ptr cloudin(results.at(FEMER_SAG)->cloud);
	pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(
			new pcl::PointCloud<pcl::PointXYZ>);
	pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(
			new pcl::PointCloud<pcl::PointXYZ>);
	// Create the filtering object
	pcl::VoxelGrid < pcl::PointXYZ > sor;
	sor.setInputCloud(cloudin);
	sor.setLeafSize(3, 3, 3);
	sor.filter(*cloud_filtered);

	std::cerr << "PointCloud after filtering: "
			<< cloud_filtered->width * cloud_filtered->height
			<< " data points (" << pcl::getFieldsList(*cloud_filtered) << ").";

	pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb(
			new pcl::PointCloud<pcl::PointXYZRGB>);

	copyPointCloud(*cloud_filtered, *cloud_xyzrgb);

	for (size_t i = 0; i < cloud_xyzrgb->points.size(); ++i) {
		cloud_xyzrgb->points[i].r = 255;
	}
	boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(
			new pcl::visualization::PCLVisualizer("3D Viewer"));
	viewer->setBackgroundColor(0, 0, 0);
	pcl::visualization::PointCloudColorHandlerRGBField < pcl::PointXYZRGB
			> rgb(cloud_xyzrgb);
	viewer->addPointCloud < pcl::PointXYZRGB
			> (cloud_xyzrgb, rgb, "sample cloud");

	viewer->setPointCloudRenderingProperties(
			pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");

	viewer->addCoordinateSystem(1, 0, 0, 100);

	viewer->initCameraParameters();

	viewer->spin();

	while (!viewer->wasStopped()) {
		double x, y, z, r, b, o;
		cout << "give x y  z \n";
		cin >> x;
		cin >> y;
		cin >> z;

		viewer->setCameraPosition(x, y, z, 0, 0, 0, 0);
		//updateCamera ();

	}

	cout << "done" << endl;

	return 0;
}