chickadee » sicp » with-mutex-locked

with-mutex-locked mutex thunkprocedure
with-mutex-locked mutex thunk conditional-variableprocedure

Evaluates the thunk having locked the mutex, unlocking it thereafter.

mutex
The mutex to lock and unlock
thunk
The thunk to evaluate
conditional-variable
An optional conditional-variable to block on at unlock
(define with-mutex-locked
  (case-lambda
    ((mutex thunk) (with-mutex-locked mutex thunk #f))
    ((mutex thunk conditional-variable)
     (dynamic-wind
       (lambda () (mutex-lock! mutex))
       thunk
       (lambda () (mutex-unlock! mutex conditional-variable))))))