我希望当一个线程找到一个新的最小值来改变它时,能够更新
许多线程同时执行的线程函数示例:
我可以使用锁来实现它,如下所示:
atomicX
。当它设置新的最小值时,我还想原子地改变变量y
。有没有一种不需要锁的方法来实现这个?许多线程同时执行的线程函数示例:
uint64_t x = atomicX;
int y = g();
for(int newX = 0; newX < x; ++newX)
{
if(f(newX))
{
while(newX < x && !atomicX.compare_exchange_strong(x, newX));
// also set atomicY to y if the exchange happened above
break;
}
x = atomicX;
}
我可以使用锁来实现它,如下所示:
int y = g();
for(uint64_t newX = 0; newX < atomicX; ++newX)
{
if(f(newX))
{
mutex.lock();
if(newX < atomicX)
{
atomicX = newX;
atomicY = y; // atomicY no longer needs to be atomic
}
mutex.unlock()
break;
}
}
我也愿意接受对此进行更清晰的结构化或者其他一起完成所有操作的方式。我不喜欢必须两次使用相同的 newX < x
条件,或者必须打破循环。
struct s { int x; int y; }; std::atomic<s>
这样的东西?在你的平台上它很可能是无锁的。这里可以查看示例。 - dypstd::atomic_flag
在 所有 平台上都保证是无锁的。 - dypint
是32位,而指针是64位。如果std::atomic
对于void*
和struct {int x; int y;};
都不是无锁的话,我会感到惊讶。 - Casey