【发布时间】:2019-07-23 08:50:51
【问题描述】:
程序:
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
void* pfun1(void *vargp);
void* pfun2(void *vargp);
void main(){
int treturn,jreturn;
pthread_t tid1,tid2;
printf("Before thread call\n");
treturn = pthread_create(&tid1,NULL,pfun1,NULL);
treturn = pthread_create(&tid2,NULL,pfun2,NULL);
jreturn = pthread_join(tid1,NULL);
//jreturn = pthread_join(tid2,NULL);
printf("After thread call\n");
}
void* pfun1(void *vargp){
int i;
for(i=0;i<5;i++){
printf("Thread1: %d\n",i);
sleep(1);
}
return (void*)0;
}
void* pfun2(void *vargp){
int i;
for(i=5;i<10;i++){
printf("Thread2: %d\n",i);
sleep(1);
}
return (void*)0;
}
在上面的程序中,我只使用 pthread_join() 将第一个线程加入到主程序中。并且第二个线程仅被创建而不附加到主线程。但是输出函数也包含第二个线程的输出。即使第二个线程没有附加到主线程,怎么可能得到它的输出?
输出:
Before thread call
Thread2: 5
Thread1: 0
Thread2: 6
Thread1: 1
Thread2: 7
Thread1: 2
Thread2: 8
Thread1: 3
Thread2: 9
Thread1: 4
After thread call
【问题讨论】:
-
pthread_join函数不是附加或启动线程,它是用来等待线程完成的。
标签: c linux multithreading ubuntu system-calls