#include #include #include #include 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 counter++; // 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", counter); return 0; }