【问题标题】:Pthread_join functionality in Linux CLinux C 中的 Pthread_join 功能
【发布时间】: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


【解决方案1】:

加入是关于同步(在加入之后,加入的线程肯定完成)并获取线程的返回值(您在每种情况下返回的(void*)0s)。

它与 IO 重定向无关。线程共享相同的 stdout/stdin(以及其他文件描述符和 stdio 缓冲区)并且立即写入(/读取)这些。在线程加入之前,它们不会被推迟。

【讨论】:

  • 如果线程共享相同的标准输入/标准输出方式,如果线程1没有加入,为什么我不能得到任何输出消息?
  • @mrg 从main 返回会杀死所有线程。他们很有可能会在他们设法输出任何东西之前被杀死。如果我在没有连接的情况下运行它,我会在某些运行时而不是在其他运行时从读取中获得输出。它对时间敏感。
【解决方案2】:

正如我从this link pthread_join 了解到的那样,只需等待 tid1 在 main 函数内重新运行,它不会阻止 tid2 输出。所以我想,如果你想在 tid1 之后运行 tid2 只需切换行:

treturn = pthread_create(&tid1,NULL,pfun1,NULL);
jreturn = pthread_join(tid1,NULL);
treturn = pthread_create(&tid2,NULL,pfun2,NULL);

目前我并不专业,因此如果您愿意,可以进行研究以获得更好的解决方案。

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多