I am writing a bit of code that implements an (unsigned) integer counter.
- It is used from an arbitrary number of threads.
- A thread should get a unique value every time until overflow.
- If integer type range is overflown, zero should be returned.
- 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
(I’m assuming that
compare_and_swaptakes a variable, a comparison value, and a swap value, and it returnstrueif the comparison succeeded (and the swap occurred).