Semaphores Flashcards
Semaphores
synchronization primitive
-can use as both locks and condition variables
- object with an integer value that we can manipulate with two routines:
1. sem_wait()
2. sem_post()
must initialize it to some value
Initializing a semaphore
sem_t s;
sem_init(&s, 0, 1)
sem_init(sem_t s, 0, value) // 0 to indicate that the semaphore is shared between threads in the same process
sem_wait
decrement the value of semaphore s by one
wait if value of semaphore is negative
sem_post()
-increments the value of the semaphore and if there is a thread waiting to be woken, wakes one of them up
Value of semaphore
- when negative, is equal to the number of waiting threads
Binary Semaphores (Locks)
-locks only have two states (held and not held), sometimes call a semaphore a binary semaphore
Scheduler State of each thread
Run: Thread is running
Read: Runnable but not running
Sleep: Thread is blocked