2

我想从在与其他线程不同的线程中运行的递归函数返回。

我尝试使用递归互斥锁,但它不起作用!

我们怎样才能实现它?

bool stop = false;
QMutex mutex(QMutex::Recursive);
int count = 1;

void worker_run () {
   QMutexLocker locker(&mutex);
   if(stop)
       return;

    qDebug () << count++;
    worker_run();

}
void worker_stop () {
    QMutexLocker locker(&mutex);
    stop = true;
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QtConcurrent::run(&worker_run);
    QtConcurrent::run(&worker_stop);

    return a.exec();
}
4

2 回答 2

2

我认为问题在于对 worker_run () 的递归调用并没有解锁互斥锁。请记住,QMutexLocker 将在超出范围时解锁。然后给它一个范围...

void worker_run () {
   { QMutexLocker locker(&mutex);
     if(stop)
       return;
   }

   qDebug () << count++;
   worker_run();
}
于 2013-08-10T22:29:31.213 回答
0

Remove all the mutexes and try again. The reason for that is because worker_run is not a critical region, except for the access to the stop variable, which is granted to be atomic.

I believe you're also missing the volatile qualifier to the stop variable (or at least, use some explicit atomic data type).

于 2013-08-10T21:54:11.927 回答