【发布时间】:2015-08-25 20:01:26
【问题描述】:
我在并行循环之前用std::pair<Object, bool> 填充了std::vector。布尔值都初始化为true。循环大致如下:
for (int x = 0; x < xMax; ++x) // can parallelising the loop in x cause a data race?
for (int y = 0; y < yMax; ++y)
for (auto& i : vector)
if (i.first.ConstantFunctionDependingOnlyOnInput(x, y))
i.second = false;
由于我们只是将布尔值设置为false,我认为这不会导致数据竞争,但我不相信我对多线程的直觉。之后对该布尔结果进行的操作在单个线程中完成(使用标准算法擦除向量中bool == true 处的所有元素。
我们将不胜感激。我打算使用std::atomics,但当然,它们不能用于std::vector,因为它们不可复制。
干杯!
【问题讨论】:
-
我的最终解决方案是使用here 所述的原子包装器,然后将布尔值设为原子。它在单线程中的执行速度非常慢,并且获得了不错的(如果不是完美的)并行加速。结果是一样的,我看不到有数据竞争,因为没有添加或删除任何元素。
标签: c++ multithreading thread-safety data-race