使用原子bool保护进程
Protecting a process with atomic bool
请假设这段代码是一个多读函数:
if( !executing_singular_process ){
executing_singular_process = true;
singular_process();
}
executing_singular_process = false;
其中executing_singular_process
为std::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同时执行你的单一进程。
相关文章:
- boost::进程间消息队列引发错误
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 为什么在保护模式下继承升级不起作用
- IPC使用多个管道和分支进程来运行Python程序
- 访问被拒绝后,c++中的故障保护代码
- C++:无法访问声明的受保护成员
- 异常属于C++中的线程还是进程
- WMI检测进程创建事件-c++
- 如何保护非托管应用程序中的字符串不受进程转储的影响
- 如何编辑受保护的进程内存?
- 创建C++守护进程并保护环境
- 终止受保护的防病毒进程
- 如何保护进程不被终止
- 写入/读取受内存保护的进程的内存
- Windows:如何在C/C++中保护进程不被杀死
- 如何保护进程免受writeprocessmemory的影响
- 如何保护两个进程之间共享内存中的字符串?
- 使用原子bool保护进程