gpt4 book ai didi

c++ - 同步主线程和工作线程

转载 作者:行者123 更新时间:2023-11-28 01:37:14 25 4
gpt4 key购买 nike

在 QT 中,我从主 (GUI) 线程创建一个工作线程来执行某个操作,该操作访问两个线程共享的资源。在 GUI 中执行某些操作时,主线程必须操作资源。我尝试使用 QMutex 来锁定该特定资源。这个资源一直被工作线程使用,如何通知主线程?尝试使用 QWaitCondition 但它导致应用程序崩溃。

是否有其他选项可以通知并实现线程间的同步?附上代码片段。

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();
}

最佳答案

您使用的等待条件完全错误。我强烈建议您阅读有关互斥锁和条件的内容,也许可以看看 some examples .

wait() 将阻止执行,直到 notify_one() 或 notify_all() 在某处被调用。这当然不会发生在您的代码中。
您不能在一行中 wait() 一个条件,然后期望接下来的两行被调用(如果它们包含唯一的唤醒调用)。

你想要的是在一个线程中使用 wait(),在另一个线程中使用 notify_XXX()。

关于c++ - 同步主线程和工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com