記今天學習Linux執行緒遇到的關於sleep(0)的問題
阿新 • • 發佈:2018-11-21
寫了一段小程式碼,目的是實現 在程序裡用pthread_create()建立新執行緒thread,然後sleep當前的main執行緒,程式就會進入剛建立的新執行緒thread,然後新執行緒thread再sleep,main執行緒sleep結束後又可以獲得CPU,如此迴圈幾次。
一開始以為第一次迴圈 i = 0時,sleep(0)是沒有作用的,但是…
程式碼如下
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
void thread (void)
{
int i;
for(i=0; i<3; i++)
{
printf("This is thread %d .\r\n",i);
sleep(i);
}
}
int main(void)
{
pthread_t id;
int i, ret;
ret = pthread_create(&id, NULL, (void*)thread, NULL);
if(ret != 0)
{
printf("Create thread error!\r\n");
exit(1);
}
for(i=0; i<3; i++)
{
printf ("This is the main thread %d .\r\n",i);
sleep(i);
}
pthread_join(id,NULL);
return(0);
}
執行結果為
看到結果覺得很奇怪,為什麼會 在main thread 0 跳到thread 0 再跳到main thread 1 ,照理來說sleep(0)應該沒什麼作用,thread 0 會繼續執行到 thread 1。
既然執行結果跟預期不一樣,肯定是哪裡沒理解好,分析了一下覺得可能是sleep(0),讓執行緒暫時讓出了CPU。
小小改動一下程式碼,把thread()的第一次迴圈的sleep(0)去掉,驗證猜想,修改後如下
void thread(void)
{
int i;
for(i=0; i<3; i++)
{
printf("This is thread %d .\r\n",i);
if(!i)
;
else
sleep(i);
}
}
果然,沒了sleep(0),執行緒thread 0 不會跳到main thread 1, 而是繼續執行for迴圈到 thread 1,說明猜想正確。
最後網上搜了一篇介紹sleep(0)作用的文章:地址
https://blog.csdn.net/qiaoquan3/article/details/56281092
文章說了sleep(0)的作用是 掛起此執行緒以使其他等待執行緒能夠執行
Thread.Sleep(0) 並非是真的要執行緒掛起0毫秒,意義在於這次呼叫Thread.Sleep(0)的當前執行緒確實的被凍結了一下,讓其他執行緒有機會優先執行。Thread.Sleep(0) 是你的執行緒暫時放棄cpu,也就是釋放一些未用的時間片給其他執行緒或程序使用,就相當於一個讓位動作。