にC++11
は、std::atomic_flag
スレッド ループに役立つ があります。
static std::atomic_flag s_done(ATOMIC_FLAG_INIT);
void ThreadMain() {
while (s_done.test_and_set()) { // returns current value of s_done and sets to true
// do some stuff in a thread
}
}
// Later:
s_done.clear(); // Sets s_done to false so the thread loop will drop out
は、スレッドがループに入らないことを意味するATOMIC_FLAG_INIT
フラグを設定します。false
(悪い)解決策は、おそらくこれを行うことです:
void ThreadMain() {
// Sets the flag to true but erases a possible false
// which is bad as we may get into a deadlock
s_done.test_and_set();
while (s_done.test_and_set()) {
// do some stuff in a thread
}
}
のデフォルトのコンストラクターはstd::atomic_flag
、フラグが未指定の状態になることを指定します。
atomic_flag
を初期化できますtrue
か? これは の正しい使い方atomic_flag
ですか?