Created
January 17, 2023 12:15
-
-
Save NonymousMorlock/5d7438ad786b947c75e22f0b3c4bf1c9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <semaphore.h> | |
| #include <pthread.h> | |
| #include <stdio.h> | |
| sem_t mutex; | |
| sem_t db; | |
| int readcount; | |
| void *reader(void *arg) | |
| { | |
| int f; | |
| sem_getvalue(&mutex, &f); | |
| printf("Reader %d is trying to enter, readcount = %d, mutex = %d\n", *((int*)arg), readcount, f); | |
| sem_wait(&mutex); | |
| readcount++; | |
| if (readcount == 1) | |
| sem_wait(&db); | |
| printf("Reader %d is inside, readcount = %d\n", *((int*)arg), readcount); | |
| sem_post(&mutex); | |
| // reading is performed here | |
| sem_wait(&mutex); | |
| readcount--; | |
| if (readcount == 0) | |
| sem_post(&db); | |
| sem_post(&mutex); | |
| printf("Reader %d is leaving, readcount = %d\n", *((int*)arg), readcount); | |
| } | |
| void *writer(void *arg) | |
| { | |
| int f; | |
| sem_getvalue(&db, &f); | |
| printf("Writer %d is trying to enter, mutex = %d, db = %d\n", *((int*)arg), f, f); | |
| sem_wait(&db); | |
| printf("Writer %d is inside\n", *((int*)arg)); | |
| // writing is performed here | |
| sem_post(&db); | |
| printf("Writer %d is leaving\n", *((int*)arg)); | |
| } | |
| int main() | |
| { | |
| pthread_t r1, r2, r3, r4, r5, w1, w2; | |
| sem_init(&mutex, 0, 1); | |
| sem_init(&db, 0, 1); | |
| readcount = 0; | |
| int a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5, a6 = 6, a7 = 7; | |
| pthread_create(&r1, NULL, reader, (void*)&a1); | |
| pthread_create(&r2, NULL, reader, (void*)&a2); | |
| pthread_create(&r3, NULL, reader, (void*)&a3); | |
| pthread_create(&r4, NULL, reader, (void*)&a4); | |
| pthread_create(&r5, NULL, reader, (void*)&a5); | |
| pthread_create(&w1, NULL, writer, (void*)&a6); | |
| pthread_create(&w2, NULL, writer, (void*)&a7); | |
| pthread_join(r1, NULL); | |
| pthread_join(r2, NULL); | |
| pthread_join(r3, NULL); | |
| pthread_join(r4, NULL); | |
| pthread_join(r5, NULL); | |
| pthread_join(w1, NULL); | |
| pthread_join(w2, NULL); | |
| sem_destroy(&mutex); | |
| sem_destroy(&db); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment