Our program demonstrates the use of atomic operations for managing a counter accessed by multiple threads. In C, we’ll use the <stdatomic.h> header for atomic operations and <pthread.h> for multi-threading.
To compile and run this program, you would typically use:
We expect to get exactly 50,000 operations. Had we used a non-atomic integer and incremented it with regular addition, we’d likely get a different number, changing between runs, because the threads would interfere with each other. Moreover, we’d get data race conditions, which can lead to unpredictable behavior.
In C, we use pthread_t to represent threads and pthread_create() to start them. The pthread_join() function is used to wait for threads to finish, similar to the WaitGroup in the original example.
The atomic_ullong type is used for the counter, and atomic_fetch_add() is used for atomic incrementation. atomic_load() is used to safely read the final value.
Note that this C code requires a C11-compatible compiler and the -lpthread flag for linking with the POSIX threads library.