I am writing开发者_Go百科 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
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).
精彩评论