V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
movq
V2EX  ›  程序员

pthread_join 为什么在这个代码里面不 block?

  •  
  •   movq · Feb 1, 2021 · 1164 views
    This topic created in 1922 days ago, the information mentioned may be changed or developed.
    #include <stdio.h>
    #include <pthread.h>
    
    void* thread(void *v) {
        printf("The thread starts now\n");
        //pthread_exit(NULL);
    }
    
    int main() {
        int tid1;
        int retValue = 0;
        pthread_create(&tid1, NULL,thread, NULL);
    
        retValue = pthread_join(tid1, NULL);
        printf("Thread ID: %d, return value: %d\n",tid1, retValue);
    
        retValue = pthread_join(tid1, NULL);
        printf("Thread ID: %d, return value: %d\n",tid1, retValue);
        return 0;
    }
    
    

    输出结果(某些时候)是:

    Thread ID: 1877241856, return value: 3
    Thread ID: 1877241856, return value: 3
    The thread starts now
    
    Process finished with exit code 0
    

    有几个疑问:

    1. 按理来说pthread_join先 block,等到thread执行完,再执行下面的语句,为什么这里不等thread执行完就继续执行了?

    2. 为什么pthread_join返回的是 3 而不是 0 ?按照定义,返回值是 0 表示正常 join

    2 replies    2021-02-01 15:30:09 +08:00
    movq
        1
    movq  
    OP
       Feb 1, 2021
    解决了,tid1 应该设置成 pthread_t 而不是 int
    crclz
        2
    crclz  
       Feb 1, 2021
    所以说不要漏掉 warning
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5888 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 06:14 · PVG 14:14 · LAX 23:14 · JFK 02:14
    ♥ Do have faith in what you're doing.