请假设这段代码是一个多线程函数:
if( !executing_singular_process ){
executing_singular_process = true;
singular_process();
}
executing_singular_process = false;
哪里executing_singular_process
是 std::atomic<bool>
.
是否存在一个线程将执行的可能性 if( !executing_singular_process )
在另一个线程中的精确时刻 if( !executing_singular_process )
和 executing_singular_process = true;
?
如果是这样,如何使用 atomic bool 来确保一个进程永远只由一个线程执行?
最佳答案
是的,两个线程可能会同时执行函数 singular_process()
。您可以使用 compare_exchange 避免此问题:
bool expected = false;
if (executing_singular_process.compare_exchange_strong(expected, true)) {
singular_process();
executing_singular_process = false;
}
关于c++ - 使用 atomic bool 保护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23619563/