Skip to content

Instantly share code, notes, and snippets.

@aahnik
Created September 12, 2023 06:44
Show Gist options
  • Save aahnik/6edc23a9a79da5637b5f995fb5feee03 to your computer and use it in GitHub Desktop.
Save aahnik/6edc23a9a79da5637b5f995fb5feee03 to your computer and use it in GitHub Desktop.
Testing Optimistic Locking
#include <pthread.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdio.h>
#define MAX 90000
atomic_int count = ATOMIC_VAR_INIT(0);
int faltu = 0;
void *incrementCount(void *arg) {
int oldValue = atomic_load(&count);
int newValue = oldValue + 1;
if (!atomic_compare_exchange_strong(&count, &oldValue, newValue)) {
printf("Increment failed\n");
}
pthread_exit(NULL);
}
void *faltuKaj(void *arg) {
faltu++;
pthread_exit(NULL);
}
int main(void) {
pthread_t threads[MAX];
int i;
for (i = 0; i < MAX; i++) {
pthread_create(&threads[i], NULL, incrementCount, NULL);
}
for (int i = 0; i < MAX; i++) {
pthread_join(threads[i], NULL);
}
pthread_t newThreads[MAX];
for (i = 0; i < MAX; i++) {
pthread_create(&newThreads[i], NULL, faltuKaj, NULL);
}
for (int i = 0; i < MAX; i++) {
pthread_join(newThreads[i], NULL);
}
printf("Count = %d\n", count);
printf("Faltu = %d\n", faltu);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment