我知道旧的 C++ 对线程一无所知,所以这是关于 IRL 编译器的 Q,不是标准的。
我最近正在编写一个代码,其中包含以下内容:
// runs until sun shines or until shutdown is signaled from another thread
// const is here just to make it clear run is not touching variable
void run(const bool& shutdown_in_progress)
{
while(! shutdown_in_progress) //1
{
//populate data
for (int i = 0; i< data.size();++i)
{
if (shutdown_in_progress) //2
break; // shutdown latency optimization
do_slow_stuff_with(data[i]);
}
}
现在假设我添加了对 shutdown_in_progress 访问的同步(这样该变量就没有竞争条件)。
我是否错误地认为编译器即使使用例如 pthread_mutex_lock/unlock 保护对 bool 的访问也可以进行破坏性优化,将 while(//1) 替换为 if 并完全删除 //2,因为它知道变量必须为 false。或者当变量被同步代码包围时,编译器有办法检测变量的可能突变?
这不是理论上的问题,我正在使用旧的 g++ 编译器开发嵌入式系统。:)