CST 334 Week 6
During this week of class, I spent most of my time learning about semaphores. A semaphore is a synchronization primitive that can be used either as a lock or a condition variable. It consists of an int value and this value plays a significant role in how it can be used for synchronization. There are several semaphore management routines, but the routines discussed in this week’s reading assignment are sem_wait and sem_post. Sem_wait, decrements the value of the semaphore and waits to see if the value is negative and sem_post increments the value and wakes a waiting thread if there is a negative semaphore. An example discussed creates a lock using a semaphore initialized to 1. When sem_wait is first called, the thread that calls it does not have to wait since the semphore’s value is not negative (sem val = 0). If or when another thread calls sem_wait, it must wait (since sem val is now negative) until the first thread calls the function sem_post. Once the original thread calls sem_post, the thread that is waiting is woken. Using this locking strategy, sem_wait and sem_post can be used around critical sections of code to ensure only one thread is active. Like mutexes, semaphores can provide mutual exclusion, but they can also be used to ensure that code within the locked region executes atomically.
The reading material from this week provided several examples of synchronization using semaphores. The buffer overflow issue in the producer/consumer problem that was resolved last week using a condition variable can also be fixed using 2 semaphores (full and empty). I also learned about how a struct using 2 semaphores and an int value for a count can be used to ensure concurrency during reading and writing operations. Additionally, the programming assignment further explored this concept with the use of condition variables and mutexes.
Comments
Post a Comment