【发布时间】:2018-02-13 06:20:55
【问题描述】:
在 QT 中,我正在从主(GUI)线程创建一个工作线程来执行某个操作,该操作访问两个线程共享的资源。在 GUI 中的某些操作上,主线程必须操作资源。我尝试使用QMutex 锁定该特定资源。这个资源一直被工作线程使用,如何通知主线程呢?
尝试使用QWaitCondition,但它使应用程序崩溃。
还有其他选项可以通知和实现线程之间的同步吗? 附上代码sn-p。
void WorkerThread::IncrementCounter()
{
qDebug() << "In Worker Thread IncrementCounter function" << endl;
while(stop == false)
{
mutex.lock();
for(int i = 0; i < 100; i++)
{
for(int j = 0; j < 100; j++)
{
counter++;
}
}
qDebug() << counter;
mutex.unlock();
}
qDebug() << "In Worker Thread Aborting " << endl;
}
//Manipulating the counter value by main thread.
void WorkerThread::setCounter(int value)
{
waitCondition.wait(&mutex);
counter = value;
waitCondition.notify_one();
}
【问题讨论】:
-
一个由两个线程共享的资源 - 你真的需要这个吗,或者工作线程可以发出一个信号让主线程代表它访问资源?跨度>
-
看起来 waitCondition.wait 需要来自其他地方的通知才能真正释放它。不熟悉QWaitCondition,但如果它基于条件变量,通常等待会挂起,直到有人通知。我没有看到与 setCounter 中的等待相对应的通知。
标签: c++ multithreading qt