随笔 - 107,  文章 - 0,  评论 - 5,  阅读 - 70476
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

背景:

在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   keleman  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示