CST 334 - Week 6
This week I learned about condition variables. Condition variables is a queue that allows threads to wait on a condition to become true, before proceeding to execute. It is another alternative to spinning locks, which is rather inefficient. Condition variables can be declared with pthread_cond_t c and offers two operations: wait(), which puts the thread to sleep, and executes with a call to signal(). wait() has mutex as a parameter so it is able to release the lock and put a thread to sleep when signaled, with the ability to reacquire the lock. I also learned the importance of using while statements over if with condition variables to ensure the thread re-checks the condition after waking up. Good practice with use of condition variables is to always hold the lock while signaling.
I also learned about semaphore, a synchronization primitive. In this, it is important to consider the execution path, as it affects what value will be printed when there are multiple threads with a shared resource. Although more complicated to use due to explicability, they replace the locks and condition variables. It can be initialized with any values, but only have two operations that are performable afterwards: increment to signal, and decrement to wait. At a negative value, the thread will block itself until another thread increments it. However, it it does not matter if the value is negative, the thread unblocks if the semaphore gets incremented. In short, if semaphore > 0, it is decremented. If semaphore = 0, operation blocks until it is able to decrement.
Comments
Post a Comment