Reputation: 31
I have to execute some heavy code in background thread by timeout. And I do not want to subclass QThread for every such workers. Is this a proper way?
/* inside QObject subclass */
auto thread = new QThread(this);
auto timer = new QTimer(nullptr);
timer->moveToThread(thread);
timer->setInterval(1000);
connect(timer, &QTimer::timeout, [](){
/* do lambda work */
});
connect(thread, SIGNAL(started()), timer, SLOT(start()));
connect(thread, &QThread::destroyed, timer, &QTimer::deleteLater);
thread->start();
Upvotes: 3
Views: 1397
Reputation: 27631
Initially the code presented looks ok. However, it depends on what you plan to do in the lambda function and what objects you're going to use and where they reside.
Your lambda function doesn't capture any variables. If this is intended, then it should be fine. However, if you're planning on using objects which have already been instantiated on the main thread, you'll have to think carefully about their thread affinity (which thread they're running on) when you try to use them in the lambda function.
Personally, I'd create a separate object, derived from QObject, which creates the QTimer and lambda function, then move that object to the new thread. Communication between this object and those on the main thread is performed via signal and slots.
Upvotes: 2