Semaphores
Notes
- This is section 6.6
- A software abstraction on top what we have seen.
- A semaphore is an ADT with the following properties
- There is an atomic unsigned integer variable, ie, zero or greater
-
S.wait()-
wait() { while value == 0 some form of waiting value-- } - Since this is an OS implemented ADT, the process/thread could be
- Stuck in a spin-lock
- Suspended and then awaken when the lock becomes available.
- (Probably the second)
-
-
S.signal()signal() { value++ }
- These can be used like a mutex (value = {0,1})
- Or as counter variables to limit access to a resource
- Say we have a queue that can only hold 5 elements.
-
SemaphoreT empty{5} SemaphoreT full{0} SemaphoreT mutex{1} queue Q ... AddMessage(message ){ empty.wait() // this will block until there is space in the queue mutex.wait() Q.enqueue(message) mutex.signal() full.signal() // this will inform the read side that there is data } GetMessage(message) { full.wait() // this will block if the queue is emtpy mutex.wait() message = Q.dequeue empty.signal() }
- Posix semaphores
-
sem_t * sem_open(const char * name, int oflags, mode_t mode, unsigned int value)- name : /somename
- oflags: O_RDWR, O_WONLY, O_RDONLY, O_EXCL, O_CREAT
- mode is optional
- value is the initial value and is optional
-
int sem_init(sem_t * sem, int shared, u nsigned int value)- sem is the semaphore from open
- shared indicates threads (0) or processes (non-zero)
- initial value
- This should only be called once.
-
sem_close(sem_t * sem) -
sem_unlink(const char * name) -
int sem_post(sem_t * sem)- Unblocks
- returns 0 on success
-
int sem_wait(sem_t * sem)and others- Blocks while the semaphore is 0,
- When it is not zero, decrements the semaphore and returns
- sem_trywait and sem_timedwait are avialable
-
- C++ has a
binary_semaphoreand acounting_semaphoreclass- reference.
- But these are for threads only.
- This is a template, and the template takes a max size
- constructor: takes the value of the semaphore
- .acquire()
- .release()
- Take a look at sem.cpp.
- Take a look at buffer.cpp.