In 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
The 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
to true
?这是正确的使用方式吗atomic_flag
?
你可以随时打电话test_and_set
在启动线程之前。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)