且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多线程中的Qt代码序列.这可能吗?

更新时间:2023-01-18 23:13:50

问题很少:

  • 函数ObjectA::run()阻止线程的事件循环;
  • A.work()是从错误的线程调用的;
  • 需要考虑正确删除A.
  • the function ObjectA::run() blocks the event loop of the thread;
  • A.work() is called from the wrong thread;
  • it is needed to think about proper deletion of A.

与其阻塞run()中的while循环,不如使用计时器.但是,在那种情况下,应该执行线程事件循环(它是在QThread::run()的默认实现中完成的.因此,应该使用其他成员插槽来启动该任务,例如:

Instead of blocking while loop in run() it is better to use timer. However, in that case the thread event loop should be executed (that it done in the default implementation of QThread::run(). So some other member slot should be used for that task to start, for example:

void ObjectA::doLoop()
{
    emit query();
    QTimer::singleShot(0, this, SLOT(doLoop()));
}

应该在启动线程时调用该函数,例如,可以通过ObjectA构造函数中的连接来完成该函数:

That function should be called when the thread is started, for example it can be done by connection in ObjectA constructor:

connect(this, SIGNAL(started()), this, SLOT(doLoop()));

***保留私有指针QTimer*,以便能够从work()停止该计时器或进行其他控制.请注意,在这种情况下,QTimer对象应该与ObjectA在同一线程中.

Even better to keep private pointer QTimer* to be able to stop that timer from work() or to have some other control. Note that in that case QTimer object should be in the same thread as ObjectA.

通常,ObjectA::work()功能应由handleQuery()的某些信号触发. ObjectA的事件循环将捕获该信号,并且work()将在ObjectA线程中启动.

Normally the ObjectA::work() function should be triggerd by some signal from handleQuery(). The event loop of ObjectA will catch that signal and the work() will be started in ObjectA thread.