MIT-Curricular/OS/C/theory/sync/semaextraposts.c

29 lines
758 B
C
Raw Normal View History

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <stdatomic.h>
atomic_int semaphore_value = 5;
sem_t *my_semaphore;
int main(){
my_semaphore = sem_open("/my_sem", O_CREAT, 0644, atomic_load(&semaphore_value));
int sem_val = atomic_load(&semaphore_value);
printf("Initial semaphore value: %d\n", sem_val);
sem_post(my_semaphore);
atomic_fetch_add(&semaphore_value, 1);
sem_post(my_semaphore);
atomic_fetch_add(&semaphore_value, 1);
sem_post(my_semaphore);
atomic_fetch_add(&semaphore_value, 1);
sem_val = atomic_load(&semaphore_value);
printf("Semaphore value after extra posts: %d\n", sem_val);
sem_close(my_semaphore);
sem_unlink("/my_sem");
return 0;
}