Assignment 4 008
Assignment 4 008
Assignment 4 008
So, sem_init(&mutex, 0, 1); initializes a semaphore named mutex with an initial value of 1,
making it suitable for basic mutual exclusion (mutex) purposes in multithreaded
programs.
sem_post(&mutex);
The sem_post(&mutex) function increments the value of the semaphore pointed to by &mutex. If
any threads were blocked waiting for this semaphore, one of them is allowed to proceed. It's
often used to signal the availability of a resource or to release a lock in a multithreaded program.
Explain what following code snippet does?
sem_t mutex,writelock
The code snippet declares two semaphores: `mutex` and `writelock`. Semaphores are synchronization
mechanisms in multithreaded programs. `mutex` is likely used for basic mutual exclusion, while
`writelock` is potentially employed to control write access to a shared resource, allowing only one thread
to write at a time.
rcount = 0;
This line initializes the `rcount` variable to 0
rcount is used to keep track of the number of active readers. Initializing it to 0 ensures no readers are
initially accessing the shared resource.
This arrangement ensures that multiple readers can access the critical section simultaneously, but
if a writer is present (locked writeblock), new readers are temporarily blocked.
Explain what following code snippet does?
void writer(void *arg) { int f; f = *((int *)arg); sem_wait(&writeblock); data++;
printf("Data writen by the writer%d is %d\n",f,data); sleep(1); sem_post(&writeblock); }
This code represents a writer function in a reader-writer problem using semaphores:
1. sem_wait(&writeblock) : Waits for the writeblock semaphore, ensuring exclusive access for
writing.
2. data++: Increments a shared variable data, representing the data being written.
3. printf("Data written by the writer%d is %d\n", f, data): Prints the updated data along with
the writer's identifier ( f).
4. sleep(1): Simulates some processing time.
5. sem_post(&writeblock) : Releases the lock, allowing other writers or readers to access the
shared data.
Explain why two nested semaphores have been used in following code snippet?
sem_wait(&empty); sem_wait(&mutex); //code here sem_post(&mutex); sem_post(&full);
The nested semaphores are likely used in a producer-consumer scenario to control access to a
shared buffer.