可以用一个pthread_t变量接收所有子线程返回吗?

迷途小码 迷途小码 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>

void *thread_function(void *arg);/*线程入口函数*/
void print(void);/*共享资源函数*/

sem_t bin_sem;/*定义信号灯*/
int value;/*定义信号灯的值*/

int main()
{
int n=0;
pthread_t a_thread;//-------------??
if((sem_init(&bin_sem,0,5))!=0)/*初始化信号灯,初始值为2*/
{
perror("sem_init");
exit(1);
}

while(n++<5)
{
if((pthread_create(&a_thread,NULL,thread_function,NULL))!=0)---------??
{
perror("Thread creation failed");
exit(1);
}
}

pthread_join(a_thread,NULL);/*等待子线程返回*/------------??
}

void *thread_function(void *arg)
{
sem_wait(&bin_sem);/*等待信号灯*/
print();
sleep(1);
sem_post(&bin_sem);/*挂出信号灯*/
printf("I finished,my pid is %d\n",pthread_self());
pthread_exit(arg);
}

void print()
{
printf("I get it,my tid is %d\n",pthread_self());
sem_getvalue(&bin_sem,&value);/*获取信号灯的值*/
printf("Now the semvalue is %d\n",value);
}

可以用a_thread等待所有线程返回,主线程再退出吗?(奇怪的是,程序运行正常)
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
迷途小码
Linux/Unix社区 23,224 成员 74,535 内容