Linux:线程和互斥量
创始人
2025-05-28 20:52:50

#include
#include
#include
#include
#include

pthread_mutex_t mutex;
char buf[50];
void * start_routine (void * arg)
{
printf(“I am child pthread0 get para %d\n”,*(int *)arg);
int b = 1001;
pthread_mutex_lock(&mutex);
*(int )arg = b;
//pthread_mutex_unlock(&mutex);
int i = 0;
for(;i<50;i++)
{
usleep(rand()%3);
buf[i] = ‘0’;
}
pthread_mutex_unlock(&mutex);
//pthread_exit(&b);
return NULL;
}
void * start_routine1 (void * arg)
{
printf(“I am child pthread1 get para %d\n”,
(int *)arg);
int b = 1002;

pthread_mutex_lock(&mutex);
//*(int *)arg = b;
// pthread_mutex_unlock(&mutex);
int i = 0;
for(;i<50;i++)
{   usleep(rand()%3);buf[i] = '1';
}
pthread_mutex_unlock(&mutex);   
//*(int *)arg = b; 
//pthread_exit(&b);
return NULL;

}

int main(int argc, const char * argv[])
{

pthread_mutex_init(&mutex, NULL);
pthread_attr_t *attr;
int a = 9;
pthread_t thread[2]; //多线程一定要定义成数组
//int ret1 = pthread_create(&thread[1], NULL,start_routine1, (void*)&a);
int ret = pthread_create(&thread[0], NULL,start_routine, (void*)&a);
int ret1 = pthread_create(&thread[1], NULL,start_routine1, (void*)&a);
if(ret != 0 || ret1 != 0 )
{printf("pthread_create fail\n");
}
ret = pthread_detach(thread[0]);
ret1 = pthread_detach(thread[1]);       
// if(ret != 0 || ret1 != 0)
// {
//     printf("pthread_detach fail\n");
// }
ret = pthread_join(thread[0], NULL);//pthread_join会让主线程等待子线程执行
ret1 = pthread_join(thread[1], NULL);//pthread_join会让主线程等待子线程执行    
if(ret != 0 || ret1 != 0)
{perror("pthread_join");int c = EINVAL;printf("ret %d, ret1 %d EINVAL=%d\n ",ret,ret1,c);//设置了pthread_detach,主线程就无法回收子线程了,返回错误码22
}sleep(1);//如果没加pthread_join,主线程要sleep等一下子线程,不然子线程没机会打印出来
int i = 0;
for(;i<50;i++)
{   printf("%c",buf[i]);
} 
printf("\n");pthread_mutex_destroy(&mutex);
printf("a= %d\n",a);
printf("pthread 0 exit with %d, pthread 1 exit with %d \n ",ret,ret1);
return 0;

}

在这里插入图片描述

相关内容

热门资讯

匈奴人长什么样子?境外考古还原... 匈奴人长什么样子?不清楚的读者可以和趣历史小编一起看下去。这是一个长期以来困扰中国人和欧洲人的大问题...
安徽汽车职业技术学院最新或20... 我院毕业生具有理论知识扎实、技能突出等优势,主要在江汽集团公司及安徽省大中型企事业单位就业。第四章 ...
邯郸之战秦国为什么会输呢 只因... 今天趣历史小编给大家准备了:邯郸之战的文章,感兴趣的小伙伴们快来看看吧!长平之战后,秦国已经战胜当时...
为什么秦国会被称为虎狼之师 而... 今天趣历史小编给大家准备了:秦国虎狼之师的文章,感兴趣的小伙伴们快来看看吧!说到我国历史上的战国时期...
秦国书同文车同轨 秦国之前的文... 还不知道:七国文字的读者,下面趣历史小编就为大家带来详细介绍,接着往下看吧~秦国的统一,不仅仅是地域...