yohhoyの日記

技術的メモをしていきたい日記

pthread_exit on main thread

POSIX Pthreadsライブラリのpthread_exit関数とメインスレッドとの関係について。本記事の内容はStackOverflowで見つけた質問と回答に基づく。

まとめ:

  • exit関数で終了:他のスレッドが実行中であってもプロセス終了する。
    • 注:main関数からのreturnはexit関数呼び出しと等価(→id:yohhoy:20120607)。
  • pthread_exit関数で終了:実行中の他スレッド処理は継続する。全スレッドが終了すると、プロセスも終了する。
    • C11標準ライブラリthrd_exit関数には関連記述みあたらず...
    • C++11標準ライブラリでは相当機能なし。*1

例えばLinuxのPthreads実装では、メインスレッドからのpthread_exit関数呼び出しについて明言されている。

NOTES
Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit(), using the function's return value as the thread's exit status.

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

(snip)

pthread_exit(3) - Linux manual page

関連URL

*1:C++では関数からのreturn以外にスレッドを終了させる手段が提供されない。