I*******g 发帖数: 7600 | 1 Imagine the following compare_and_swap (CAS) primitive function is available
to
you. Using this function, write an integer counter class providing increment,
decrement, set and get APIs in an atomic and thread-safe way in a context
subject to
periodic highly intensive concurrent activity .
/* In a critical section, if (*dest) == old_val, then updates dest to new_
val and returns true otherwise leaves dest unchanged and returns false.
*/
bool compare_and_swap(int* dest, int old_val, int new_val) | I*******g 发帖数: 7600 | 2 要求用C++
available
increment,
【在 I*******g 的大作中提到】 : Imagine the following compare_and_swap (CAS) primitive function is available : to : you. Using this function, write an integer counter class providing increment, : decrement, set and get APIs in an atomic and thread-safe way in a context : subject to : periodic highly intensive concurrent activity . : /* In a critical section, if (*dest) == old_val, then updates dest to new_ : val and returns true otherwise leaves dest unchanged and returns false. : */ : bool compare_and_swap(int* dest, int old_val, int new_val)
| z******g 发帖数: 271 | 3 class AtomicCounter {
private:
volatile int mem;
public:
AtomicCounter(): mem(0) {}
int get() { return mem; }
void inc() {
int new_val, old_val;
do {
old_val = mem;
new_val = old_val + 1;
} while(!compare_and_swap(&mem, old_val, new_val));
}
void dec() {
// same
}
}; |
|