简体   繁体   English

Qt应用程序中的线程自定义调度

[英]Custom scheduling of threads in Qt application

I am a new-comer to Qt and would like to know about recommended approaches towards custom scheduling of threads managed by QThread instances. 我是Qt的新手,想了解有关QThread实例管理的线程的自定义调度的推荐方法。

I would like to have a scheduler thread which, in response to change in application state, puts certain threads to sleep or changes their priority. 我想拥有一个调度程序线程,该线程可响应应用程序状态的更改,使某些线程进入睡眠状态或更改其优先级。 The scheduling should be preemptive as in I should be able to put to sleep certain workers (which may be waiting on a mutex) and invoke them later. 调度应该是抢先的,因为我应该能够使某些工作人员(可能正在等待互斥体)入睡,并在以后调用它们。

What I am particularly curious about is why the QThread::sleep and related functions are protected ? 我特别好奇的是,为什么QThread :: sleep和相关功能受到保护?

If the kind of fine grained control over scheduling can't be obtained through Qt threading classes then I would like to know about alternative possibilities. 如果无法通过Qt线程类获得对调度的精细控制,那么我想了解其他可能性。

So do there exist ways to make other threads sleep and later wake them up ? 那么,是否存在使其他线程休眠并随后唤醒它们的方法?

Making threads sleep when out of work is not usually the most efficient or cleanest way to accomplish what you need. 通常,使线程在不工作时进入睡眠状态并不是通常最有效或最干净的方式来完成所需的工作。 You generally want to keep threads alive when they have work and destroy them when they don't (instead of forcing stagnant threads to sleep repeatedly). 通常,您希望线程在工作时保持活动状态,而在线程不工作时将其销毁(而不是让停滞的线程重复睡眠)。 The idiomatic way to manage threads in Qt is utilizing the signal /slot interface to facilitate the creation and destruction of threads. 在Qt中管理线程的惯用方式是利用信号/插槽接口来促进线程的创建和销毁。

Here is a simple example from the QThread documentation that shows how this feature of Qt can be used to handle thread scheduling with little outside intervention: 这是QThread文档中的一个简单示例,显示了如何使用Qt的此功能以很少的外部干预来处理线程调度:

 class Worker : public QObject
 {
     Q_OBJECT

 public slots:
     void doWork() {
         ...
     }
 };

 void MyObject::putWorkerInAThread()
 {
     Worker *worker = new Worker;
     QThread *workerThread = new QThread(this);

     connect(workerThread, SIGNAL(started()), worker, SLOT(doWork()));
     connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
     worker->moveToThread(workerThread);

     // Starts an event loop, and emits workerThread->started()
     workerThread->start();
 }

For more advanced threading schemes, Qt also provides additional threading mechanisms (that utilize signals & slots) like QThreadPool or anything in the QtConcurrent namespace. 对于更高级的线程方案,Qt还提供了其他线程机制(利用信号和插槽),例如QThreadPoolQtConcurrent命名空间中的任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM