0% found this document useful (0 votes)
56 views2 pages

Implementation of Semaphores Oslab

This code implements semaphores to synchronize access to a shared resource between two threads. It initializes a mutex semaphore with an initial value of 1, allowing only one thread to enter the critical section protected by the semaphore at a time. The two threads call sem_wait to wait their turn and sem_post to signal when done, ensuring the printf statements from each thread are not interleaved. The main thread joins the two threads before destroying the semaphore.

Uploaded by

theonlygod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views2 pages

Implementation of Semaphores Oslab

This code implements semaphores to synchronize access to a shared resource between two threads. It initializes a mutex semaphore with an initial value of 1, allowing only one thread to enter the critical section protected by the semaphore at a time. The two threads call sem_wait to wait their turn and sem_post to signal when done, ensuring the printf statements from each thread are not interleaved. The main thread joins the two threads before destroying the semaphore.

Uploaded by

theonlygod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Submitted by: Abhishek Kandel(19BCE2629)

Implementation Of Semaphores

Code:
#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

sem_t mutex;

void* thread(void* arg)

sem_wait(&mutex);

printf("\nThis is has been Entered..\n");

sleep(4);

printf("\nThis is Exiting...\n");

sem_post(&mutex);

int main()

sem_init(&mutex, 0, 1);

pthread_t t1,t2;

pthread_create(&t1,NULL,thread,NULL);

sleep(2);

pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL);

pthread_join(t2,NULL);

sem_destroy(&mutex);

printf("\ndone by abhishek kandel.");

return 0;

Output:

Thank You!!!

You might also like