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()
callsexit()
(p36) Options for detached threads
https://github.com/boostcon/2011_presentations/raw/master/wed/boehm-boostcon11.pdf
- 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.)
関連URL