|
queue buffer producer() while true buffer.put( makeWidget()) consumer() while true munge(buffer.get())
|
queue.put(w): if size < n size++ b[tail] = w tail = (tail + 1) mod n queue.get(): if size > 0 size-- w = b[head] head = (head + 1) mod n return w
size
= 0).
consumer producer buffer.put(w)
if size < n
size++
context switch w = buffer.get()
if size > 0
size--
w = b[head]
size
< n - 2 with two producers.
producer1 producer2 buffer.put(w)
if size < n
size++
b[tail] = w
context switch buffer.put(w)
if size < n
size++
b[tail] = w
put()
and get()
calls.
queue.put(w): if size < n size++ b[tail] = w tail = (tail + 1) mod n queue.get(): if size > 0 size-- w = b[head] head = (head + 1) mod n return w
queue.put(w): disableinterrupts() if size < n size++ b[tail] = w tail = (tail + 1) mod n ensableinterrupts() queue.get(): disableinterrupts() if size > 0 size-- w = b[head] head = (head + 1) mod n ensableinterrupts() return w
mutex.lock()
- get the key, lock the mutex. Block if the key’s
not available.
mutex.unlock()
- Unlock the mutex, return the key. Wake up a
thread blocked during a lock.
unlock()
.
mutex buffermutex // unlocked to start queue buffer // empty to start producer: while true widget w = makeWidget() buffermutex.lock() buffer.put(w); buffermutex.unlock() consumer: while true buffermutex.lock() widget w = buffer.get() buffermutex.unlock() munge(w)
pthread_mutex_t m int pthread_mutex_lock( pthread_mutex_t *mutex) int pthread_mutex_trylock( pthread_mutex_t *mutex) int pthread_mutex_unlock( pthread_mutex_t *mutex)
trylock()
doesn’t block, but
returns false
when it tries to lock a locked mutex.
class ProtectedQueue private Queue q; synchronous put(e) q.put(e) synchronous get() return q.get() ProtectedQueue pbuffer producer() while true pbuffer.put(makeWidget()) consumer() while true munge(pbuffer.get())
class mutex private bool locked void lock() if locked wait until unlocked lock = true void unlock lock = false if waiting threads wake one up
m
is unlocked.
thread1 thread2 m.lock()
if locked
context switch m.lock()
if locked
locked = true
context switch locked = true
void lock() disableinterrupts() if locked wait until unlocked lock = true enableinterrupts() void unlock() disableinterrupts() lock = false if waiting threads wake one up enableinterrupts()
void lock() disableinterrupts() if locked wait until unlocked lock = true enableinterrupts()
void lock() disableinterrupts() if locked enableinterrupts() wait until unlocked disableinterrupts() lock = true enableinterrupts() void unlock() disableinterrupts() lock = false if waiting threads wake one up enableinterrupts()
m
.
thread1 thread2 thread3 m.lock()
disable interrupts()
if locked
enable interrupts()
wait
context switch m.unlock()
context switch m.locked()
context switch disable interrupts()
lock = true
enable interrupts()
|
|
|
|
This page last modified on 2012 February 13. |