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

迷途小码 2009-09-16 11:04:30
#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等待所有线程返回,主线程再退出吗?(奇怪的是,程序运行正常)
...全文
151 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
nevil 2009-09-16
  • 打赏
  • 举报
回复
if((sem_init(&bin_sem,0,5))!=0)
你信号量的初始值为5,而创建了4个线程,因此没有一个线程会阻塞。

你的pthread_join(a_thread,NULL)只是等待你最后一个创建的线程。

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧