Sleep(0)与Sleep(1)区别

博客讨论了在线程调度中Sleep(0)和Sleep(1)的区别。Sleep(1)会让线程释放时间片并等待至少1毫秒,而Sleep(0)则仅放弃剩余时间片,线程立即变为就绪状态。在同等优先级下,Sleep(0)的线程更可能抢占执行机会。了解这些细节对于优化多线程程序的性能至关重要。
摘要由CSDN通过智能技术生成

1、问题

在线程中我们会经常按如下写代码,Sleep(0)比Sleep(1)更容易获得时间片

DWORD WINAPI SampleThread(PVOID pvParam)
{
	while ( true )
	{
        // do something
        Sleep(1);
	}
	return 0x50;
}

2、原因

MSDN说明如下:


Remarks
This function causes a thread to relinquish the remainder of its time slice and become unrunnable for at least the specified number of milliseconds, after which the thread is ready to run. In particular, if you specify zero milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the specified interval elapses. For more information, see Scheduling Priorities.

 

Sleep(1)导致线程释放剩余的时间片,并停止运行至少1毫秒,然后恢复为就绪状态。

Sleep(0)导致线程释放剩余的时间片,并立即进入就绪状态。

所以如果有两个同等优先级的线程一个使用Sleep(1),一个使用Sleep(0),后者将更多的抢到时间片。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值