背景:

在QThread的run函数中执行耗时工作。
示例代码

void wakeThread::run()
{
m_waitcondition.wait(); #1

	if(getThreadState()==STOP) #2
	{
	 break;
	}
	
	for(int i=0;i<1000;++)      #3
	{
		QThread::sleep(1);
	 ....
	 ....
	}

}

问题:

多个线程(A,B)用同一个m_waitcondition 来唤醒。
当该线程(A)正在执行 #3处的代码时,其他线程(B)由通过 m_waitconditiong.wakeall(),再次唤醒线程A,
(1)这时还会马上再次执行#3处的代码吗?
(2)还是等#3处的代码执行后在执行第二次唤醒,再次执行#3

答案:

通过做了个示例表明

(1)不会执行#3处代码,

(2)等#3处的代码执行完后,不会执行第二次唤醒再来执行#3处代码。而是重新进入等待唤醒的状态,即第二次唤醒对该m_waitcondition 不起作用

原因是已经是唤醒的状态了(不是等待状态),不用再唤醒。

以下为引用 qt 官方文档

Also, if some of the threads are still in do_something() when the key is pressed, they won't be woken up 	(since they're not waiting on the condition variable) and so the task will not be performed for that key 	press.
posted on 2024-01-05 10:10  keleman  阅读(31)  评论(0编辑  收藏  举报