#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
#define NUM_INCREMENTS 1000000
atomic_int counter = 0;
void *thread_func(
UNUSED void *arg) {
for (int i = 0; i < NUM_INCREMENTS; ++i) {
}
return NULL;
}
int main(void) {
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_create(&threads[i], NULL, thread_func, NULL) != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("Final counter value: %d (Expected: %d)\n", final,
NUM_THREADS * NUM_INCREMENTS);
return 0;
}
Atomic operation macros and typedefs using GCC/Clang __atomic_* builtins.
#define ATOMIC_INC(Ptr)
Atomically increment the value and return the new value.
Definition atomics.h:121
#define DEFINE_ATOMIC(Type)
Declares a volatile (atomic) type.
Definition atomics.h:135
#define ATOMIC_LOAD(Ptr)
Load the value atomically from the given pointer.
Definition atomics.h:77
Convenience macros for GCC function, variable, and type attributes.
#define UNUSED
Marks a variable or function as possibly unused to suppress warnings.
Definition util_attributes.h:213