【发布时间】:2016-10-04 07:14:23
【问题描述】:
这是 pthread_create 的声明:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *
(*start_routine) (void *), void *arg);
它包含一个函数 start_routine。
所以当我们调用 pthread_create 时,该函数将使用参数 arg 执行。
那为什么要调用 pthread_join(),因为要执行 start_routine 函数?
我也尝试不包含 pthread_join( ) 函数,确实 start_routine 函数根本没有执行,进程创建后就退出了。
那么当程序来到 pthread_create 时,它究竟会发生什么?参数 start_routine 的执行是否有条件?
令人困惑...
这是我的测试代码:
#include <pthread.h>
#include <stdio.h>
int sum;
void* runner(void *param);
int main(int argc, char *argv[])
{
pthread_t tid; //The thread identifier
pthread_attr_t attr;//set of thread attributes
if(argc!=2){
fprintf(stderr, "usage:a.out <integer value>\n");
return -1;
}
if(atoi(argv[1])<0){
fprintf(stderr, "%d must be <=0\n",atoi(argv[1]));
return -1;
}
//get the default attributes
pthread_attr_init(&attr);
//create the thread
pthread_create(&tid,&attr,runner,argv[1]);
//now wait for the thread to exit
pthread_join(tid,NULL);
printf("sum=%d\n", sum);
}
void* runner(void *param)
{
int i,upper = atoi(param);
sum=0;
for(i=1;i<=upper;i++)
sum+=i;
pthread_exit(0);
}
【问题讨论】:
标签: linux process pthread-join