自学内容网 自学内容网

多线程编程实例

代码:

#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资源造成的


原文地址:https://blog.csdn.net/chenbingjy/article/details/142711297

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!