chapter 31 - semaphores Flashcards
(11 cards)
What is a semaphore
A semaphore holds a counter representing the number of allowed accesses to a resource
sem_wait() and sem_post() operations
what does a semaphore value say
semaphore’s value represents how many “resources” are available
What does sem_wait() do?
If the value > 0, it decrements and continues. If ≤ 0, the thread blocks and waits
Wait until the resource is available, then take one
What does a semaphore value < 0 mean?
That many threads are blocked waiting
What does sem_post() do?
Increments the value; if threads are waiting, one is unblocked
What’s a binary semaphore used for?
As a lock for mutual exclusion
How are semaphores initialized?
With sem_init(). Third argument sets initial value; second is 0 for use between threads
How can semaphores be used as locks?
Binary semaphores (1=unlocked) act like mutexes
sem_wait() = lock
sem_post() = unlock
What happens when two threads use a binary semaphore as a lock?
One thread enters at a time.
Others wait (block) until it’s released.
When the holder calls sem_post(), the next waiting thread is woken up
Producer/Consumer: What does the empty semaphore track?
How many empty slots are left in the buffer
Initialized to buffer size
Producer/Consumer: What does the full semaphore track?
How many filled slots are in the buffer - initialized to 0