enzom83
enzom83

Reputation: 8320

How to manage a thread using an event loop?

I created a class MyThread to process incoming data from the network using a separate thread. Basically, I created a multi-client server, as it receives the data, adds them to a shared queue. The thread MyThread gets the data from the shared queue until it is present at least one element in this queue.

void MyThread::run()
{
    while (true)
    {
        _mutex.lock();
        if (_stopping)
        {
            _stopping = false;
            _mutex.unlock();
            break;
        }
        _mutex.unlock();

        QString data;
        if (_queue.dequeue(data))
        {
            process(data);
        }
    }
}

Now I should use a timer within this thread, because I need to periodically change some data within the class MyThread. In this regard, I have read the documentation available on this page, but I should use an event loop within the thread MyThread. How to change the class MyThread to manage the thread with an event loop?

Upvotes: 1

Views: 167

Answers (1)

Tim Meyer
Tim Meyer

Reputation: 12600

The easiest way to get an event loop in QThread is to not subclass it. The default implementation of QThread::run() calls QThread::exec() which starts an event loop.

This means the code which is currently in your run() override would have to go into a separate worker class, meaning you separate the actual work from the thread control, which also makes your code a lot more flexible.

There is an example in the QThread Documentation; I highly recommend the first example which does not subclass QThread.

Upvotes: 3

Related Questions