V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
movq
V2EX  ›  程序员

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

  •  
  •   movq · 2021-02-01 14:41:17 +08:00 · 791 次点击
    这是一个创建于 1181 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #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 条回复    2021-02-01 15:30:09 +08:00
    movq
        1
    movq  
    OP
       2021-02-01 15:19:04 +08:00
    解决了,tid1 应该设置成 pthread_t 而不是 int
    crclz
        2
    crclz  
       2021-02-01 15:30:09 +08:00
    所以说不要漏掉 warning
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5378 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 108ms · UTC 06:00 · PVG 14:00 · LAX 23:00 · JFK 02:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.