Created
September 12, 2023 06:44
-
-
Save aahnik/6edc23a9a79da5637b5f995fb5feee03 to your computer and use it in GitHub Desktop.
Testing Optimistic Locking
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 <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