可以用一个pthread_t变量接收所有子线程返回吗?
#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等待所有线程返回,主线程再退出吗?(奇怪的是,程序运行正常)
#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等待所有线程返回,主线程再退出吗?(奇怪的是,程序运行正常)
...全文
相关推荐
Posix多线程编程
介绍Posix多线程编程,linux 多线程开发、锁机制等
linux创建线程之pthread_create的具体使用
pthread_create函数 函数简介 pthread_create是UNIX环境创建线程函数 头文件 #include 函数声明 int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg); 返回值 若成功则返回0,否则返回出错编号 参数 第一个参数为指向线程标识符的指针。 第二个参数用来设置线程属性。 第三个参数是线程运行函数的地址。 最后一个参
C语言如何正确的终止正在运行的子线程
主要介绍了C语言如何正确的终止正在运行的子线程,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
pthread_cond_wait() 用法深入分析
以下是对pthread_cond_wait的用法进行了详细的分析介绍,需要的朋友可以过来参考下
由浅入深Linux下pthread线程库介绍
由浅入深Linux下pthread线程库介绍,pthread在linux下面的实现,与posix的标准


