yohhoyの日記

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

detachスレッドとプログラム終了処理

C++11におけるdetach済みスレッドとexit関数で引き起こされる問題についてメモ。

あるスレッドでstd::exit関数が呼ばれて終了処理中に、残存するdetach済みスレッドがライブラリ関数を呼び出して未定義動作を引き起こす危険性がある。下記の回避策がありえる:

  • プログラム終了処理の前にdetachスレッド完了を待機する。ただしthread::join関数を使えないため、別のスレッド完了待ち同期機構を実装しなければならない。(そもそもdetachした意味は?)
  • std::quick_exit関数を利用する。
  • スレッドdetachを利用しない。

BoostCon 2011スライド資料 "Threads and Shared Variables in C++0x, Hans-J. Boehm" より引用。

(p35) A note on detached threads:

  • C++ static destructors can cause problems:
    • (図は省略)
  • Even standard library is unsafe to use after exit()
    • except that threads may return after main() calls exit()

(p36) Options for detached threads

  • Wait for them to terminate, possibly after some sort of shutdown request.
    • Unfortunately, there is no thread cancellation.
    • But then why detach?
  • Exit without calling static destructors (quick_exit())
  • Just don’t call detach(). (My personal favorite.)
https://github.com/boostcon/2011_presentations/raw/master/wed/boehm-boostcon11.pdf

関連URL