Exercise: Implement atomic counter
Multiple threads running counter = counter + 1;
could leads to unexpected results due to GCC/Compiler generates multiple assembly instructions for assignment.
Multiprocess, thread switching, device interrupt could lead to invalid results.
Example program uses counter = counter + 1
Result
Use atomic operation
Replace the counter = counter + 1
, with __sync_fetch_and_add(&counter, 1);
Purpose
This function atomically adds the value of v to the variable that p points to. The result is stored in the address that is specified by __p.
A full memory barrier is created when this function is invoked.
Prototype
T __sync_fetch_and_add (T* __p, U __v, ā¦);
Parameters
__p
The pointer of a variable to which v is to be added. The value of this variable is to be changed to the result of the add operation. `v` The variable whose value is to be added to the variable that p points to. Return value The function returns the initial value of the variable that p points to.
Expected Result
Last updated