c - Linux C 中的 Pthread_join 功能

标签 c linux multithreading ubuntu system-calls

程序:

#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/

相关文章:

java - 多线程中的线程池

c - 循环或多线程哪一个执行时间较长?

c++ - 在哪里可以找到所有数学函数的描述,比如 floorf 和其他函数?

无法在 C 代码中模仿 `echo` 命令的 Action

c - 为什么我必须在 &ip_reply->saddr 中使用 "&"

python - 我们可以在 Python 中使用 C 代码吗?

arrays - sh + 如何在 sh 中使用数组来打印数组中的所有值

c++ - 使用 NSOpenGLView 进行线程渲染

c - 理解定点运算

c - 设计一个算法来判断是否存在这样一个键等于数组中其他两个键的总和