ENع
→Monitors
الدرس 22 · Synchronisation

Monitors

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة12 خطوة5 أسئلةIntermediate
عن هذا الدرس

Locks and condition variables work, but they are easy to misuse: forget one unlock and every thread is stuck. A monitor packs the shared data, its lock and its condition variables into one object, and only the object's methods may touch the data. Follow two threads through a tiny bank account monitor: one wants to withdraw 5 from an empty account and must wait, the other deposits 10 and wakes it. You will see the two queues every monitor has, and why a woken thread must check its condition again. The Software lesson Threads and concurrency shows the race these tools prevent, and the Condition variables lesson in this module explains wait and signal on their own.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 22 · تفاعلي
01 / 12

Data, lock and queue in one

A monitor bundles shared data, here a bank balance, with one lock and a condition variable. Threads may only reach the data by calling the monitor's methods, and the monitor takes and gives back the lock for them.

monitor Account
  data        balance = 0
  lock        one, taken on entry, given back on exit
  condition   funds: a queue of threads waiting for money
  methods     withdraw(n), deposit(n): the only way in

Brinch Hansen (1973), Hoare (1974): a lock and zero or
more condition variables, packed with the data they guard
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Data, lock and queue in one

    A monitor bundles shared data, here a bank balance, with one lock and a condition variable. Threads may only reach the data by calling the monitor's methods, and the monitor takes and gives back the lock for them.

    monitor Account
      data        balance = 0
      lock        one, taken on entry, given back on exit
      condition   funds: a queue of threads waiting for money
      methods     withdraw(n), deposit(n): the only way in
    
    Brinch Hansen (1973), Hoare (1974): a lock and zero or
    more condition variables, packed with the data they guard
  2. T1 enters and takes the lock

    Thread T1 calls withdraw(5). Calling any monitor method first takes the monitor lock. The lock is free, so T1 takes it and walks in. While T1 holds it, T1 is the only thread active inside.

    T1   withdraw(5)
    line 2   with lock:      take the monitor lock
    lock          free -> T1
    inside        T1
    entry queue   (empty)
  3. One thread at a time

    Thread T2 calls deposit(10) at the same moment. Its first move is to take the lock, but T1 holds it. So T2 waits outside in the entry queue. No two threads ever run inside together.

    T2   deposit(10)
    line 7   with lock:      lock is held by T1
    T2            sleeps in the entry queue
    lock          T1
    entry queue   T2
    mutual exclusion: at most one thread inside
  4. T1 checks the balance

    Inside, T1 tests its condition: is balance less than 5? The balance is 0, so T1 cannot go on. It must wait until another thread adds money.

    line 3   while balance < n:
                 0 < 5   true: not enough money
    T1 holds the lock, so the balance cannot change
    while it looks: the test is safe
  5. Waiting gives the lock back

    T1 calls funds.wait(). In one step it joins the funds queue, goes to sleep and releases the lock. If it slept holding the lock, T2 could never get in to deposit and both would be stuck.

    line 4   funds.wait()
    atomically:   T1 joins the funds queue
                  T1 sleeps
                  the lock is released
    lock          T1 -> free
    funds queue   T1
  6. T2 gets in and deposits

    The lock is free, so T2, first in the entry queue, takes it and walks in. It adds 10: the balance goes from 0 to 10. T1 is still asleep in the funds queue.

    lock          free -> T2
    line 8   balance += n
    balance       0 -> 10
    funds queue   T1 (asleep)
  7. notify() wakes T1, T2 stays

    T2 calls funds.notify(), which wakes one thread from the funds queue. T1 wakes, but T2 still holds the lock and keeps running. So T1 joins the entry queue: it must win the lock again before it can go on.

    line 9   funds.notify()
    funds queue   T1 -> (empty)
    entry queue   T1  (woken, needs the lock again)
    lock          still T2: notify() does not release it
    this is Mesa semantics: signal and continue
  8. T2 leaves, the lock passes on

    T2 reaches the end of its with block. Leaving the method gives the lock back, and T2 walks out, its deposit done. T1, first in the entry queue, can now take the lock.

    line 7   end of the with block: release the lock
    T2            done
    lock          T2 -> free (T1 is next in line)
    entry queue   (empty)
  9. T1 checks again

    Holding the lock again, T1 returns from wait() to the top of its while loop and tests once more. Now the balance is 10, not less than 5, so the loop ends.

    lock          free -> T1
    wait() returns with the lock held by T1
    line 3   while balance < n:
                 10 < 5   false: leave the loop
  10. T1 withdraws and leaves

    T1 takes 5: the balance goes from 10 to 5. Then it leaves the monitor and gives the lock back. Both calls are done, and no update was ever lost.

    line 5   balance -= n
    balance       10 -> 5
    lock          T1 -> free
    both threads done; queues empty
  11. Why while, not if

    Between notify() and T1 getting the lock, another thread could slip in first and take the money. A wake-up is only a hint, so a woken thread must test its condition again. That is why the test is a while loop.

    Hoare (1974)   signal hands the lock straight to the
                   woken thread: the condition still holds
    Mesa (1980)    signal only makes it runnable; the
                   signaller keeps the lock (this lesson)
    
    nearly every real system uses Mesa semantics, and
    wait() may also wake for no reason (spurious wake-up)
    -> always: while not condition: wait()
  12. Monitors in real code

    Java builds monitors into the language: every object has a lock, and synchronized methods take it. Python and C have no monitor keyword, so you build the same object from a lock and a condition variable.

    the same monitor in C99 with POSIX threads:
    
    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <stdio.h>
    
    static int balance = 0;
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t funds = PTHREAD_COND_INITIALIZER;
    
    static void withdraw(int n) {
        pthread_mutex_lock(&lock);          /* enter */
        while (balance < n)
            pthread_cond_wait(&funds, &lock);
        balance -= n;
        pthread_mutex_unlock(&lock);        /* leave */
    }
    
    static void deposit(int n) {
        pthread_mutex_lock(&lock);
        balance += n;
        pthread_cond_signal(&funds);
        pthread_mutex_unlock(&lock);
    }
    
    static void *t1(void *arg) { (void)arg; withdraw(5); return NULL; }
    static void *t2(void *arg) { (void)arg; deposit(10); return NULL; }
    
    int main(void) {
        pthread_t a, b;
        pthread_create(&a, NULL, t1, NULL);
        pthread_create(&b, NULL, t2, NULL);
        pthread_join(a, NULL);
        pthread_join(b, NULL);
        printf("balance %d\n", balance);
        return 0;
    }
    
    prints:
    balance 5
    
    and as a Python program:
    
    import threading
    
    balance = 0
    lock = threading.Lock()
    funds = threading.Condition(lock)   # a condition tied to the lock
    waiting = threading.Event()
    
    def withdraw(n):
        global balance
        with lock:                       # enter: take the monitor lock
            while balance < n:
                print("T1 waits: balance", balance)
                waiting.set()
                funds.wait()             # release lock, sleep, re-take lock
            balance -= n
            print("T1 took", n, "-> balance", balance)
    
    def deposit(n):
        global balance
        with lock:
            balance += n
            print("T2 put", n, "-> balance", balance)
            funds.notify()               # wake one waiter; T2 keeps the lock
    
    t1 = threading.Thread(target=withdraw, args=(5,))
    t1.start()
    waiting.wait()                       # start T2 once T1 is waiting
    t2 = threading.Thread(target=deposit, args=(10,))
    t2.start()
    t1.join(); t2.join()
    print("balance", balance)
    
    prints:
    T1 waits: balance 0
    T2 put 10 -> balance 10
    T1 took 5 -> balance 5
    balance 5

اختبار يتاح بعد الخطوة الأخيرة.