使用原子bool保护进程

Protecting a process with atomic bool

本文关键字:保护 进程 bool      更新时间:2023-10-16

请假设这段代码是一个多读函数:

if( !executing_singular_process ){
    executing_singular_process = true;
    singular_process();
}
executing_singular_process = false;

其中executing_singular_processstd::atomic<bool>

是否存在一个线程在if( !executing_singular_process )executing_singular_process = true;之间的另一个线程执行if( !executing_singular_process )的精确时刻?

如果是的话,如何使用原子bool来确保一个进程只能由一个线程执行?

是的,两个线程可以同时执行singular_process()函数。使用compare_exchange:

可以避免这个问题
bool expected = false;
if (executing_singular_process.compare_exchange_strong(expected, true)) {
    singular_process();
    executing_singular_process = false;
}

除了在nosid的回答中指出的,你的代码还有另一个巨大的问题,即使没有你自己发现的安全漏洞(它在nosid的回答中也被修复了)

让我们假设你的代码有3个线程在运行:

线程A获得原子bool,将其设置为true,执行单进程。现在线程B到达,找到一个真。线程跳过singular_process,但现在将原子bool设置为true!但是线程A可能仍然在单进程上工作!所以当线程C到达初始检查时,你的bool告诉它,执行单一进程是完全可以的。突然间,A和C同时执行你的单一进程。