没有锁或互斥的原子比较

时间:2022-04-18 21:01:14

I'm trying to do an exercise which uses atomic operations. I want to do a comparison between a position of atomic array and an atomic int using compare_exchange.
My code is:

我正在尝试进行使用原子操作的练习。我想使用compare_exchange对原子数组的位置和原子int进行比较。我的代码是:

std::array<std::atomic<long int>, 20> xx;
std::atomic<long int> number;

I want to do:

我想要做:

if (xx[i] > number)
  number = xx[i];

How can use compare_exchange_weak() in my case? I saw a lot of times http://en.cppreference.com/w/cpp/atomic/atomic but I don't understand it.

在我的情况下如何使用compare_exchange_weak()?我看过很多次http://en.cppreference.com/w/cpp/atomic/atomic但我不明白。

1 个解决方案

#1


2  

You can't. std::atomic allows various atomic operations on a single object. To perform an atomic operation involving more than one object, you'll need a lock.

你不能。 std :: atomic允许对单个对象进行各种原子操作。要执行涉及多个对象的原子操作,您需要锁定。

compare_exchange, as your link describes, atomically compares the object for equality with a non-atomic value, and updates it depending on that comparison. It doesn't compare two atomic values.

compare_exchange,正如您的链接所描述的那样,原子地将对象与非原子值进行相等性比较,并根据该比较对其进行更新。它不比较两个原子值。

#1


2  

You can't. std::atomic allows various atomic operations on a single object. To perform an atomic operation involving more than one object, you'll need a lock.

你不能。 std :: atomic允许对单个对象进行各种原子操作。要执行涉及多个对象的原子操作,您需要锁定。

compare_exchange, as your link describes, atomically compares the object for equality with a non-atomic value, and updates it depending on that comparison. It doesn't compare two atomic values.

compare_exchange,正如您的链接所描述的那样,原子地将对象与非原子值进行相等性比较,并根据该比较对其进行更新。它不比较两个原子值。