多线程编程实例

代码:

#include<stdio.h>
#include<pthread.h>
static int run=-1;
static int retvalue;
void *start_routine(void *arg)
{
	int *running =arg;
	printf("child Thread initial over,pass in parameters:%d\n",*running);
	while(*running)
	{
		printf("child thread is running\n");
		usleep(1);
	}
	printf("child thread quit\n");
	retvalue=8;
	pthread_exit((void*)&retvalue);
}
int main(void)
{
	pthread_t pt;
	int ret=-1;
	int times=3;
	int i=0;
	int *ret_join=NULL;
	ret=pthread_create(&pt,NULL,(void*)start_routine,&run);
	if(ret!=0)
	{
		printf("create thread failed!\n");
		return 1;		
	}
	usleep(1);
	for(;i<times;i++)
	{
		printf("main thread print\n");
		usleep(1);
	}		
	run=0;
	pthread_join(pt,(void*)&ret_join);
	printf("thread back value is:%d\n",*ret_join);
	return 0;
}

运行

第一次:

第二次

前后两次结果不一致,主要是两个线程争夺CPU资源造成的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值