{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

notes13 - Semaphores generalization of mutexes initial...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Semaphores: - generalization of mutexes - initial count >= 0 pseudocode: sema_wait(sem)  { sem->count--; if(sem->count < 0) { //wait } } sema_post(sem)  { sem->count++; //wake up one thread waiting on semaphore if any } - three ways of using semaphores: - n == 0 – make a thread wait until event happens sema_t sem sema_init(&sem,0) T1    T2 count = 0 sema_wait(&sem) count = -1 //wait count = -1 sema_post(&sem) count = 0 //wakeup T1 //continue - n == 1 – semaphore is equivalent to a mutex sema_t sem mutex_init(&sem,1) T1 count  = 1 sema_wait(&sem) count = 0 // continue         count = 0 sema_wait(&sem) count = -1 //block sema_post(&sem) //wake up T2 continue
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
- n > 1 – controls access to resources that have a maximum  number of units sema_init(&sem,3) T1 T2 T3 T4 count = 3 sema_wait(&sem) count = 2 //continue count = 2 sema_wait(&sem) count = 1 //continue count =1 sema_wait(&sem) count = 0 //continue count = 0 sema _wait(&sem) count  = -1 //block count = -1 sema_post(&sem) count  = 0 //wak e up T4 Bounded Buffer: - problem: producer threads and consumer threads communicate    using a circular buffer (circular queue). - new entries are added at the tail and entries are removed from the   head. - head and tail wrap around when they reach the end. - the get() method will block until there is an entry in the buffer (not    empty). - the put() method will block until there is space in the buffer and then    it will add an entry. - the circullar buffer can be used by multiple threads simultaneously.                              put()                                              get() T1   T4 T2   T5 T3   T6    producer       consumer - implementation:
Background image of page 2
typedef void * MsgType; class BoundedCircularBuffer  {
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}