class semaphore { public semaphore(unsigned c) : cnt(c) { } void p(void) { <wait cnt > 0 ; cnt = 0> } void v(void) { <cnt = 1> } private unsigned cnt }
v()
atomicity is important
p()
wake-up behavior varies - one or all; which one
// Bad - x write conflicts int x = ... co x = ... x ... || x = ... x ... oc |
// Good - no write conflicts int x = ... semaphore x_mutex(1) co x_mutex.lock() x = ... x ... x_mutex.unlock() || x_mutex.lock() x = ... x ... x_mutex.unlock() oc |
p()
, and unlock for v()
struct disk_controller { semaphore mutex(1) word command_reg word blockno_reg word address_reg word results_reg }
cnt <= 1
cnt >= 0
void d() { <wait cnt > 0 ; cnt--> }
void v() { <cnt++> }
d()
- it varies from
implementation to implementation, and it can get funky
count()
- return the number of stones in the bowl; negative
numbers indicate the number of waiters.
locked()
- return true iff the semaphore is locked
bool try_lock()
- lock the semaphore if open
semaphore s(1) co s.down() || s.up() oc
This page last modified on 27 June 2002.