是否有必要调用pthread_join()

nav*_*jan 13 c multithreading pthreads

我从main()创建了超过100个线程所以我只想知道在退出main()之前需要调用pthread_join().此外,我不需要这些线程生成的数据,基本上所有线程都在做一些独立于main()和其他线程的工作.

Ste*_*sop 26

pthread_join 做两件事:

  1. 等待线程完成.
  2. 清理与线程关联的所有资源.

如果退出的过程中不加入,那么(2)会为你由OS来完成(尽管它不会做线程取消清理,只是核弹从轨道线),以及(1)不会.所以你是否需要打电话pthread_join取决于你是否需要(1)发生.

如果你不需要线程运行,那么正如其他人所说的那样你也可以分离它.分离的线程无法连接(因此您无法等待其完成),但如果资源完成,则会自动释放其资源.


Sha*_*ain 6

是的,如果线程是可附加的,那么pthread_join它是必须的,否则它会创建一个僵尸线程。

我同意上面的答案,只是分享pthread_join.

笔记:

   After a successful call to pthread_join(), the caller is guaranteed that the target thread has terminated.

   Joining with a thread that has previously been joined results in undefined behavior.

   Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread".  Avoid doing this, since each zombie thread consumes some  system  resources,  and  when
   enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).
Run Code Online (Sandbox Code Playgroud)