34 lines
908 B
C
Raw Normal View History

#include <stdatomic.h>
2025-02-08 12:08:00 +05:30
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <dispatch/dispatch.h>
2025-02-08 12:08:00 +05:30
atomic_int counter = 0; // shared resource
dispatch_semaphore_t semaphore; // semaphore declaration
2025-02-08 12:08:00 +05:30
void* increment(void* arg) {
for (int i = 0; i < 100000; i++) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // lock
atomic_fetch_add(&counter, 1); // critical section
dispatch_semaphore_signal(semaphore); // unlock
2025-02-08 12:08:00 +05:30
}
return NULL;
}
int main() {
pthread_t t1, t2;
semaphore = dispatch_semaphore_create(1); // initialize semaphore with value 1
2025-02-08 12:08:00 +05:30
pthread_create(&t1, NULL, increment, NULL);
pthread_create(&t2, NULL, increment, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
dispatch_release(semaphore);
2025-02-08 12:08:00 +05:30
printf("Final Counter Value (with semaphores): %d\n", atomic_load(&counter));
2025-02-08 12:08:00 +05:30
return 0;
}