Do you think PROTECTED QThread::sleep() method should be made PUBLIC ?
-
To create a new thread, it is more and more advocated not to subclass QThread but instead to create a Worker class and then to move the worker object to the new thread by using moveToThread().
I prefer this method too. It makes the code much more clear and logic. However there is a drawback. We can’t use static QThread::sleep() method anymore because this method is protected.
There are always workarounds like the one I propose below but I’d like to know if you think as I do that Qt should now consider making this static method PUBLIC so that we can simply sleep like that in the worker code ? :
@
QThread::currentThread()->sleep(5);
@The workaround below consists in subclassing QThread to MThread to make sleep() public and then to sleep by casting currentThread() to MThread before calling MThread public sleep().
@
class MThread : public QThread {
Q_OBJECT
public:
MThread(QObject *parent) : QThread(parent) {}
static void sleep(unsigned long secs) { QThread::sleep(secs);}
};class Worker : public QObject {
Q_OBJECT
public :
Worker(){}
Q_INVOKABLE void task1() {
qDebug() << "Worker::task1() - begin - Thread=" << QThread::currentThreadId();
static_cast<MThread *>(QThread::currentThread())->sleep(5);
qDebug() << "Worker::task1() - end - Thread=" << QThread::currentThreadId();
}
….
}int main(int argc, char *argv[]) {
QApplication app(argc, argv);
qDebug() << "main() - ThreadId =" << QThread::currentThreadId();
Worker *worker = new Worker;
QThread *thread = new QThread;
thread->start();
worker->moveToThread(thread);
QMetaObject::invokeMethod(worker, "task1");
….
}
@Also, if you can think about a more simple workaround, please let me know.
Gilles, Paris
-
sleep() is made public in Qt 5: http://doc-snapshot.qt-project.org/5.0/qthread.html -- That doesn't help users of Qt 4.8, unfortunately.
If your code involves a repeating loop, with sleeping between each iteration, you can try using QTimer to call the function at regular intervals
-
Thanks for the info. That's good news.