程序:
#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() 将第一个线程加入到主程序中。而第二个线程只是被创建而没有附加到main。但是输出函数也包含第二个线程的输出。为什么即使第二个线程没有连接到主线程也可以获得它的输出?
输出:
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
最佳答案
加入就是同步(加入之后,加入的线程肯定结束了)和获取线程的返回值(每种情况下返回的(void*)0
) .
与IO重定向无关。线程共享相同的 stdout/stdin(以及其他文件描述符和 stdio 缓冲区)并立即写入(/读取)这些内容。它们不会被推迟,直到线程被加入。
关于c - Linux C 中的 Pthread_join 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942636/