记今天学习Linux线程遇到的关于sleep(0)的问题

写了一段小代码,目的是实现 在进程里用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,也就是释放一些未用的时间片给其他线程或进程使用,就相当于一个让位动作。

猜你喜欢

转载自blog.csdn.net/qq_40541268/article/details/84260388