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

45 lines
1.1 KiB
C

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <stdatomic.h>
atomic_int counter = 0; // shared resource
sem_t *semaphore; // semaphore declaration
void* increment(void* arg) {
for (int i = 0; i < 100000; i++) {
sem_wait(semaphore); // lock
atomic_fetch_add(&counter, 1); // critical section
sem_post(semaphore); // unlock
}
return NULL;
}
int main() {
pthread_t t1, t2, t3, t4;
// MacOS specific semaphore definition.
semaphore = sem_open("/mysem", O_CREAT, 0644, 1);
if (semaphore == SEM_FAILED) {
perror("sem_open failed");
return 1;
}
pthread_create(&t1, NULL, increment, NULL);
pthread_create(&t2, NULL, increment, NULL);
pthread_create(&t3, NULL, increment, NULL);
pthread_create(&t4, NULL, increment, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
sem_close(semaphore);
sem_unlink("/mysem");
printf("Final Counter Value (with semaphores): %d\n", atomic_load(&counter));
return 0;
}