Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create qt thread event loop

I am using Qt in order to write a GUI application.

A main thread is responsible for the GUI and creates an QThread in order to do some work with an object.

class Worker
{
    void start() {
        QTimer* timer = new Timer();
        connect(timer,SIGNAL(timeout()),this,SLOT(do()));
    }

    void do() {
        //do some stuff
        emit finished();
    }
}



class GUI
{
    //do some GUI work then call startWorker();

    void startWorker() {
        QThread* thread = new Thread();
        Worker* worker = new Worker();

        worker->moveToThread(thread);

        connect(thread, SIGNAL(started()), worker, SLOT(start()));
        connect(worker, SIGNAL(finished()), workerthread, SLOT(quit()));
        connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
    }
}

Now I have several problems:

  1. The timer in my worker class does not work. Maybe it is because the new thread has no event loop, but I have no idea how to create such one. I tried

    connect(workerthread, SIGNAL(started()), workerthread, SLOT(exec()));

    but it does not work either.

  2. When I try to wait on the new thread, the signal is never sent

    class GUI
    {
        void exit() {
            thread->wait();
        }
    }
    

I think it also is because there is no event loop and because of that no signal is emitted.

Does anybody have an idea how to solve these problems?

like image 338
Sven Jung Avatar asked Apr 02 '13 21:04

Sven Jung


1 Answers

why not use qthreadpool, than you make your task class inherits from qrunnable and qobject, this way you can use signals and slots to pass data from one thread to another, is much simpler to implement, and increase performance from not recreating a thread or having one sleeping all the time

class myTask : public QObject, public QRunnable{
Q_OBJECT

protected:
void run(); //where you actually implement what is supposed to do

signals:
void done(int data);//change int to whatever data type you need

}

//moc click example, or use a timer to call this function every x amount of time
void button_click(){
   myTask *task = new myTask();
   task->setAutoDelete(true);
   connect(task,SIGNAL(done(int)),this,SLOT(after_done(int)),Qt::QueuedConnection);
   QThreadPool::globalInstance()->start(task);
}

by default you application gets 1 thread automatically, which you can use to handle the graphic, than use the qthreadpool to process the data/object on demand, you can even set the max amount of threads your application can use to process new request, the others will stay in a queue until one thread is freed

QThreadPool::globalInstance()->setMaxThreadCount(5);
like image 81
LemonCool Avatar answered Sep 25 '22 08:09

LemonCool