chickadee » srfi-18 » mutex-unlock!

mutex-unlock! mutex #!optional condition-variable timeoutprocedure

Unlocks the mutex by making it unlocked/not-abandoned. It is not an error to unlock an unlocked mutex and a mutex that is owned by any thread. If condition-variable is supplied, the current thread is blocked and added to the condition-variable before unlocking mutex; the thread can unblock at any time but no later than when an appropriate call to condition-variable-signal! or condition-variable-broadcast! is performed (see below), and no later than the timeout (if timeout is supplied). If there are threads waiting to lock this mutex, the scheduler selects a thread, the mutex becomes locked/owned or locked/not-owned, and the thread is unblocked. mutex-unlock! returns #f when the timeout is reached, otherwise it returns #t.

NOTE: The reason the thread can unblock at any time (when condition-variable is supplied) is to allow extending this SRFI with primitives that force a specific blocked thread to become runnable. For example a primitive to interrupt a thread so that it performs a certain operation, whether the thread is blocked or not, may be useful to handle the case where the scheduler has detected a serious problem (such as a deadlock) and it must unblock one of the threads (such as the primordial thread) so that it can perform some appropriate action. After a thread blocked on a condition-variable has handled such an interrupt it would be wrong for the scheduler to return the thread to the blocked state, because any calls to condition-variable-broadcast! during the interrupt will have gone unnoticed. It is necessary for the thread to remain runnable and return from the call to mutex-unlock! with a result of #t.

NOTE: mutex-unlock! is related to the "wait" operation on condition variables available in other thread systems. The main difference is that "wait" automatically locks mutex just after the thread is unblocked. This operation is not performed by mutex-unlock! and so must be done by an explicit call to mutex-lock!. This has the advantages that a different timeout and exception handler can be specified on the mutex-lock! and mutex-unlock! and the location of all the mutex operations is clearly apparent. A typical use with a condition variable is:

    (let loop ()
      (mutex-lock! m)
      (if (condition-is-true?)
            (mutex-unlock! m))
            (mutex-unlock! m cv)