CST 334 Week 6 Journal Entry

Semaphores

Semaphores are synchronization primitives that can help manage shared resources. They are variables associated with an underlying counter that can be any integer. Atomic operations can be applied to a semaphore, which will ensure that threads access shared resources in a controlled and orderly manner. 

Two functions can be used to implement a semaphore: sem_wait and sem_post. The function sem_wait() is called before a critical section of code and decrements the value of a semaphore. If the semaphore is positive, then shared resources are available, and a thread may have access to the critical section. In this case, the semaphore's value is decremented, and the function returns. If it is zero or negative, shared resources are unavailable, and the thread is blocked from the critical section. In this case, the thread has to wait until the semaphore value is positive to access the critical section. 

The function sem_post() is called at the end of a critical section of code. Once the thread has completed the critical section, sem_post is called, and the value of the semaphore is incremented. The function then wakes up one waiting thread so that it may have access to the critical section.

Semaphores can be used in producer/consumer scenarios. In this scenario, semaphores can be used as signals to track the number of empty and full slots in a buffer. The producer waits for the buffer to become empty before putting data in the buffer, while the consumer waits for the buffer to be filled to use the needed data. To ensure processes are synchronized, the function sem_wait needs to be called before the producer can put data. Once data has been entered into the buffer, a signal is sent that new data is available using sem_post. The consumer calls sem_wait before attempting to get the data from the buffer. After the data is obtained, the function sem_post would need to be called to signal that space is now available. 

Comments

Popular posts from this blog

CST 300 - Week 8

CST 300 - Week 5

CST 300 - Week 4