朴素布尔否定
std::atomic_bool b; b = !b;
似乎不是原子的。我怀疑这是因为 operator! 触发了对普通 bool 的转换。一个人将如何原子地执行等价的否定?下面的代码说明天真的否定不是原子的:
operator!
bool
#include <thread> #include <vector> #include <atomic> #include <iostream> typedef std::atomic_bool Bool; void flipAHundredThousandTimes(Bool& foo) { for (size_t i = 0; i < 100000; ++i) { foo = !foo; // Launch nThreads std::threads. Each thread calls flipAHundredThousandTimes // on the same boolean void launchThreads(Bool& foo, size_t nThreads) { std::vector<std::thread> threads; for (size_t i = 0; i < nThreads; ++i) { threads.emplace_back(flipAHundredThousandTimes, std::ref(foo)); for (auto& thread : threads) thread.join(); int main() { std::cout << std::boolalpha; Bool foo{true}; // launch and join 10 threads, 20 times.