开发者

How to handle integer overflows with atomic increment and compare-and-swap operations?

开发者 https://www.devze.com 2023-04-04 23:04 出处:网络
I am writing开发者_Go百科 a bit of code that implements an (unsigned) integer counter. It is used from an arbitrary number of threads.

I am writing开发者_Go百科 a bit of code that implements an (unsigned) integer counter.

  1. It is used from an arbitrary number of threads.
  2. A thread should get a unique value every time until overflow.
  3. If integer type range is overflown, zero should be returned.
  4. I have at my disposal atomic increment function (returns old value), and atomic compare-and-swap function.

All scenarios I have come up with so far suffer from race conditions on overflow. Is it possible to implement the counter with these constraints?


You can build everything from compare-and-swap. The general algorithm is

int DoSomeAtomicCalculation()
{
    static int value;
    int capture, newValue;
    do {
        capture = value;
        newValue = some_function_based_on(capture);
    } while (!compare_and_swap(value, capture, newValue));
    return newValue;
}

(I'm assuming that compare_and_swap takes a variable, a comparison value, and a swap value, and it returns true if the comparison succeeded (and the swap occurred).

0

精彩评论

暂无评论...
验证码 换一张
取 消