pthread_join是如何实现的?

Tom*_*Tom 10 linux multithreading scheduling pthreads

我对线程有点新意,所以你必须原谅这个问题的天真.

如何pthread_join实现以及它如何影响线程调度?

我总是想象pthread_join用while循环实现,只是导致调用线程屈服,直到目标线程完成.像这样(非常近似的伪代码):


atomic bool done;

thread_run {

    do_stuff();
    done = true;

}

thread_join {

    while(!done) {
        thread_yield();
    //  basically, make the thread that calls "join" on
    //  our thread yield until our thread completes
    }
}

这是一个准确的描述,还是我过分简化过程?

干杯!

Nik*_*sov 6

是的,这是一般的想法。有关特定实现的详细信息,请查看glibc

  • 他的代码和真实代码之间唯一真正大的区别是,如果有一个备用内核,他的代码会导致连接线程100% 地消耗CPU。 (2认同)

Mar*_*rkR 5

pthread_join可能在内部实现为等待信号量,该信号量在线程退出时(无论是调用pthread_exit还是其主函数退出)都会触发。

无论如何,都可以使用glibc的源代码,请尝试使用Google代码搜索(我在那里看到了一些有用的东西)

  • https://sourceware.org/git/?p=glibc.git;a=blob;f=nptl/pthread_join.c;h=6a87a8b329c3e34a57d65e86d45fa97a5fdb2fe2;hb=master#l89 用于神奇发生的行。 (2认同)