Skip to content

Instantly share code, notes, and snippets.

@Hotshot824
Last active December 31, 2023 09:00
Show Gist options
  • Save Hotshot824/c2b4d3b073159c91f2a8e3bf11a37271 to your computer and use it in GitHub Desktop.
Save Hotshot824/c2b4d3b073159c91f2a8e3bf11a37271 to your computer and use it in GitHub Desktop.
compare-exchange-spinlock.c
#include <stdio.h>
#include <stdatomic.h>
#include <pthread.h>
#define NUM_THREADS 4
int counter = 0;
void* incrementCounter(void* arg) {
int* id = (int*)arg;
int value = 0;
for (int i = 0; i < 10000000; ++i) {
do {
value = counter;
/* If compare exchange fails, value while be updated to the current value of counter. */
} while (!atomic_compare_exchange_weak(&counter, &value, value + 1));
}
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS] = {0, 1, 2, 3};
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_create(&threads[i], NULL, incrementCounter, &thread_ids[i]);
}
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
}
printf("Spinlock counter value: %d\n", counter);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment