记今天学习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,也就是释放一些未用的时间片给其他线程或进程使用,就相当于一个让位动作。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值