

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
how semaphore mutual exclusion works and code in c as example
Typology: Study notes
1 / 3
This page cannot be seen from the preview
Don't miss anything!


Semaphore is a synchronization primitive used in concurrent programming to control access to a shared resource. Mutual exclusion using semaphores ensures that only one process or thread can access the shared resource at a time. Here’s how semaphore mutual exclusion works: Explanation:
#include <stdio.h> #include <pthread.h> #include <semaphore.h> #define NUM_THREADS 5 Sem_t mutex; // Semaphore for mutual exclusion Void *thread_function(void *thread_id) { Int tid = *((int *)thread_id); Printf(“Thread %d is attempting to acquire the semaphore.\n”, tid); Sem_wait(&mutex); // Acquire the semaphore Printf(“Thread %d has acquired the semaphore and is now accessing the shared resource.\n”, tid); // Access the shared resource (critical section) Printf(“Thread %d is releasing the semaphore.\n”, tid); Sem_post(&mutex); // Release the semaphore Pthread_exit(NULL); } Int main() { Pthread_t threads[NUM_THREADS]; Int thread_ids[NUM_THREADS]; Sem_init(&mutex, 0, 1); // Initialize the semaphore with value 1 For (int I = 0; I < NUM_THREADS; ++i) { Thread_ids[i] = I; Pthread_create(&threads[i], NULL, thread_function, (void *)&thread_ids[i]); } For (int I = 0; I < NUM_THREADS; ++i) {