Last active
November 9, 2022 10:05
-
-
Save r00takaspin/1b0727bb77f90b1af7edfe834f1da976 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <assert.h> | |
pthread_mutex_t lock; | |
int counter = 0; | |
#define MAX_ITER 100000 | |
void* writer(void *arg) { | |
for(int i=0; i < MAX_ITER; i++) | |
{ | |
pthread_mutex_lock(&lock); | |
counter += 1; | |
pthread_mutex_unlock(&lock); | |
} | |
return NULL; | |
} | |
int main() { | |
int writers_num = 8; | |
pthread_t tid_writers[writers_num]; | |
if (pthread_mutex_init(&lock, NULL) != 0) | |
{ | |
printf("\n mutex init failed\n"); | |
return 1; | |
} | |
for (int i=0; i < writers_num; i++) | |
{ | |
if (pthread_create(&(tid_writers[i]), NULL, &writer, &i)!=0) | |
{ | |
printf("\ncannot create writer thread\n"); | |
exit(0); | |
} | |
} | |
for(int i=0; i < writers_num; i++) | |
{ | |
pthread_join(tid_writers[i], NULL); | |
} | |
pthread_mutex_destroy(&lock); | |
assert((MAX_ITER*writers_num==counter) && "counter failed"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment