-
-
Save Hotshot824/c2b4d3b073159c91f2a8e3bf11a37271 to your computer and use it in GitHub Desktop.
compare-exchange-spinlock.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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