我遇到的情况是,根据 GUI 上的用户操作,线程正在运行时我必须终止该线程。我在 Windows 上使用 Qt 4.5.2。一种方法如下:
class MyThread : public QThread
{
QMutex mutex;
bool stop;
public:
MyThread() : stop(false) {}
void requestStop()
{
QMutexLocker(&mutex);
stop = true;
}
void run()
{
while(counter1--)
{
QMutexLocker(&mutex);
if (stop) return;
while(counter2--)
{
}
}
}
};
请注意,上面的代码是最少的。 run 函数最多可能需要 20 秒才能完成,因此我想避免在循环中锁定和解锁 mutex
变量。有没有比这个方法更快的方法。
提前致谢。
最佳答案
它不能直接满足您的需求,但您不能更严格地限定互斥体的范围吗?
while(counter1--) {
{
QMutexLocker(&mutex);
if (stop) return;
} // End locking scope : we won't read it anymore until next time
while(counter2--)
...
关于c++ - 如何根据用户请求安全地停止正在运行的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1681429/