CST 334 - Module 6

 Week 6,

    This week’s module was a continuation of maintaining concurrency between multiple threads. Like last week, we use pthreads to do your average threading activities, only difference is that instead of using pthread condition variables along with the pthread functions related to it, we instead use semaphores. The cool thing about the semaphore is that it can be used as both the lock and the condition due to it using an integer. Additionally, because it uses an integer, we can also use it to control which thread starts first. 

    The main idea is if you call the function sem_wait(), you decrement the integer, and if you call sem_post(), you increment the integer and signal a waiting thread. The reason for incrementing and decrementing is that if a thread calls sem_wait() and the integer ends up returning negative, the thread that called sem_wait() must now sleep. Once a thread that was allowed to continue before hand (sem_wait() returned 0 or higher when the thread called it) finishes its critical section and calls sem_post() the integer value increases and wakes a thread that is waiting. If the incremented value returns 0 or higher, the waiting thread can continue. Essentially, any thread that calls sem_wait() and it returns a positive integer or zero holds the lock.

    Depending on how we initialize the semaphore, we can have it act as a lock mutex, or as a way to make threads work in a certain order. For example, initializing the semaphore to 1 or higher, makes it function as a lock. Initializing the semaphore to 0 makes it act as an orderer.


Comments

Popular posts from this blog

CST 300 - Module 4

CST 300 - Module 2

CST 300 - Module 3