//counting semaphore semaphore: maxsize count = 0 lock = new int acquire(): lock(lock): while count == maxsize: monitor.wait(lock) if count == 0: monitor.pulseall(lock) return ++count // returns 1..maxsize int release(): lock(lock): while count == 0: monitor.wait(lock) if count == maxsize: monitor.pulseall(lock) return --count // returns 0..maxsize-1
// below statements are equivalent lock(lock): // do something monitor.enter(lock) try: // do something finally: monitor.exit(lock)Note:
- pulse/all when count is 1+ does nothing
- pulse/all when count is (maxsize-1)- does nothing
As there will be no threads in waiting queue to be moved to ready queue.
[Hat tip to MG]
No comments:
Post a Comment