ENع
→Classic sync problems
الدرس 23 · Synchronisation

Producer-consumer, readers-writers and dining philosophers

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

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

Three famous puzzles show up again and again in real programs. A producer and a consumer share a small buffer. Many readers and an occasional writer share some data. Five philosophers share five forks. Watch each one run step by step: semaphores count free and filled slots, a reader count lets readers share while a writer waits, and a fixed lock order breaks a deadly circle of waiting. The lessons on semaphores and monitors build the tools used here, and the Software lesson on threads and concurrency shows the race they prevent.

ستتعلّم

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

شكل 23 · تفاعلي
01 / 11

A buffer between two threads

A producer thread makes items and a consumer thread uses them. Between them is a buffer with 3 slots. Semaphore empty counts free slots (3), full counts filled slots (0), and mutex (1) lets one thread touch the buffer at a time.

the bounded buffer (OSTEP Figure 31.12, CS162 lecture 8)

sem_init(&empty, 0, 3);   /* free slots   */
sem_init(&full,  0, 0);   /* filled slots */
sem_init(&mutex, 0, 1);   /* a lock        */

producer must wait when the buffer is full
consumer must wait when the buffer is empty
only one thread at a time may change the buffer
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A buffer between two threads

    A producer thread makes items and a consumer thread uses them. Between them is a buffer with 3 slots. Semaphore empty counts free slots (3), full counts filled slots (0), and mutex (1) lets one thread touch the buffer at a time.

    the bounded buffer (OSTEP Figure 31.12, CS162 lecture 8)
    
    sem_init(&empty, 0, 3);   /* free slots   */
    sem_init(&full,  0, 0);   /* filled slots */
    sem_init(&mutex, 0, 1);   /* a lock        */
    
    producer must wait when the buffer is full
    consumer must wait when the buffer is empty
    only one thread at a time may change the buffer
  2. Putting an item

    To put item A, the producer calls sem_wait(empty): 3 becomes 2, so a slot is reserved. It takes the mutex, writes A into slot 0, gives the mutex back, then calls sem_post(full): 0 becomes 1. One item is ready.

    producer, one item (C99, POSIX semaphores):
    
    sem_wait(&empty);   empty 3 -> 2   (would sleep at 0)
    sem_wait(&mutex);   mutex 1 -> 0   (lock)
    buf[in] = 'A';      slot 0 = A
    in = (in + 1) % 3;
    sem_post(&mutex);   mutex 0 -> 1   (unlock)
    sem_post(&full);    full  0 -> 1
  3. The buffer fills up

    The producer puts B and C the same way. Now empty is 0 and full is 3. For item D, sem_wait(empty) finds 0, so the producer is put to sleep. It does not spin or overwrite a slot: it waits.

    item   empty   full   slots
    A      2       1      A _ _
    B      1       2      A B _
    C      0       3      A B C
    D      sem_wait(&empty) finds 0: the producer sleeps
    
    sem_wait(3): if the value is above zero, decrement and return;
    otherwise block until the decrement becomes possible
  4. Taking wakes the producer

    The consumer calls sem_wait(full): 3 becomes 2. It takes A from slot 0 under the mutex, then calls sem_post(empty). That post wakes the sleeping producer, which puts D into the freed slot 0.

    consumer                  empty  full   slots
    sem_wait(&full)             0     2     A B C
    take A (under the mutex)    0     2     _ B C
    sem_post(&empty)            1     2     wakes the producer
    producer finishes its wait  0     2
    puts D, sem_post(&full)     0     3     D B C
    
    the whole program (C99, POSIX; build with -pthread):
    
    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <semaphore.h>
    #include <stdio.h>
    
    #define SLOTS 3
    #define ITEMS 4
    static char buf[SLOTS];
    static int in, out;
    static sem_t empty, full, mutex;
    
    static void *producer(void *arg) {
        (void)arg;
        for (int i = 0; i < ITEMS; i++) {
            sem_wait(&empty);            /* wait for a free slot */
            sem_wait(&mutex);
            buf[in] = (char)('A' + i);
            in = (in + 1) % SLOTS;
            sem_post(&mutex);
            sem_post(&full);             /* one more filled slot */
        }
        return NULL;
    }
    
    static void *consumer(void *arg) {
        (void)arg;
        for (int i = 0; i < ITEMS; i++) {
            sem_wait(&full);             /* wait for a filled slot */
            sem_wait(&mutex);
            char c = buf[out];
            out = (out + 1) % SLOTS;
            sem_post(&mutex);
            sem_post(&empty);            /* one more free slot */
            putchar(c);
        }
        putchar('\n');
        return NULL;
    }
    
    int main(void) {
        pthread_t p, c;
        sem_init(&empty, 0, SLOTS);      /* 0: shared by threads */
        sem_init(&full, 0, 0);
        sem_init(&mutex, 0, 1);
        pthread_create(&p, NULL, producer, NULL);
        pthread_create(&c, NULL, consumer, NULL);
        pthread_join(p, NULL);
        pthread_join(c, NULL);
        return 0;
    }
    
    prints   ABCD
  5. Many readers at once

    Readers only look at the shared data, so any number may read together. The first reader in locks writers out; later readers just add 1 to the count. Here two readers read v1 at once, and readers = 2.

    a simple reader-writer lock (OSTEP Figure 31.13):
    
    typedef struct {
        sem_t lock;        /* guards readers */
        sem_t writelock;   /* one writer or many readers */
        int readers;
    } rwlock_t;
    
    static void read_lock(rwlock_t *rw) {
        sem_wait(&rw->lock);
        if (++rw->readers == 1) sem_wait(&rw->writelock); /* first in */
        sem_post(&rw->lock);
    }
    static void read_unlock(rwlock_t *rw) {
        sem_wait(&rw->lock);
        if (--rw->readers == 0) sem_post(&rw->writelock); /* last out */
        sem_post(&rw->lock);
    }
    static void write_lock(rwlock_t *rw)   { sem_wait(&rw->writelock); }
    static void write_unlock(rwlock_t *rw) { sem_post(&rw->writelock); }
    
    R1 read_lock   readers 1   first in: takes writelock
    R2 read_lock   readers 2   just counts
  6. A writer waits its turn

    A writer changes the data, so it needs it alone. It waits on the write lock. Each reader that leaves subtracts 1, and the last one out, at readers = 0, unlocks. Only then does the writer write v2.

    W  write_lock      readers 2   writelock is held: W sleeps
    R1 read_unlock     readers 1   still not 0
    R2 read_unlock     readers 0   last out: sem_post(writelock)
    W  wakes, writes   data v1 -> v2   (alone)
    
    the same lock as a whole program (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <semaphore.h>
    #include <stdio.h>
    
    typedef struct {
        sem_t lock;        /* guards readers */
        sem_t writelock;   /* one writer or many readers */
        int readers;
    } rwlock_t;
    
    static void read_lock(rwlock_t *rw) {
        sem_wait(&rw->lock);
        if (++rw->readers == 1) sem_wait(&rw->writelock); /* first in */
        sem_post(&rw->lock);
    }
    static void read_unlock(rwlock_t *rw) {
        sem_wait(&rw->lock);
        if (--rw->readers == 0) sem_post(&rw->writelock); /* last out */
        sem_post(&rw->lock);
    }
    static void write_lock(rwlock_t *rw)   { sem_wait(&rw->writelock); }
    static void write_unlock(rwlock_t *rw) { sem_post(&rw->writelock); }
    
    int main(void) {
        rwlock_t rw = { .readers = 0 };
        sem_init(&rw.lock, 0, 1);
        sem_init(&rw.writelock, 0, 1);
        read_lock(&rw); read_lock(&rw);
        printf("readers = %d\n", rw.readers);
        read_unlock(&rw); read_unlock(&rw);
        write_lock(&rw);
        printf("writer in, readers = %d\n", rw.readers);
        write_unlock(&rw);
        return 0;
    }
    
    prints
    readers = 2
    writer in, readers = 0
  7. Writers can starve

    In this simple lock a new reader may join whenever the count is above 0. If readers keep overlapping, the count never reaches 0 and the writer waits forever: starvation. Fairer locks hold new readers back while a writer waits.

    readers over time   1 2 1 2 1 2 1 2 1
    writer still waiting: yes
    
    OSTEP: "it would be relatively easy for readers to starve writers"
    
    POSIX pthread_rwlock_rdlock (with priority scheduling):
      a reader gets in only if no writer holds the lock
      and no writer is blocked on it
    Linux kernel: rw_semaphore and rwlock_t are
      "multiple readers and single writer" locks
  8. Five philosophers, five forks

    Five philosophers sit at a round table with one fork between each pair. To eat, philosopher p needs both forks beside it: left fork p and right fork (p + 1) mod 5. Each fork is a lock that only one may hold.

    Dijkstra, 1971 (EWD310): spaghetti eaten "with two forks"
    
    int left(int p)  { return p; }
    int right(int p) { return (p + 1) % 5; }
    
    philosopher   left fork   right fork
    P0            0           1
    P1            1           2
    P2            2           3
    P3            3           4
    P4            4           0
    
    neighbours share a fork, so they cannot eat at the same time
  9. Everyone grabs left

    Suppose all five pick up their left fork at the same moment. Every fork is now held, and each philosopher waits for its right fork, held by its neighbour. The waiting forms a circle, so nobody can ever eat: deadlock.

    void get_forks(int p) {           /* broken */
        sem_wait(&forks[left(p)]);
        sem_wait(&forks[right(p)]);
    }
    
    fork 0  held by P0   P0 waits for fork 1 (P1)
    fork 1  held by P1   P1 waits for fork 2 (P2)
    fork 2  held by P2   P2 waits for fork 3 (P3)
    fork 3  held by P3   P3 waits for fork 4 (P4)
    fork 4  held by P4   P4 waits for fork 0 (P0)
    
    P0 -> P1 -> P2 -> P3 -> P4 -> P0   a circle of waiting
    eating: nobody
  10. Break the circle

    The fix: always pick up the lower-numbered fork first. Philosopher 4 needs forks 4 and 0, so it reaches for fork 0 first and loses it to philosopher 0. Fork 4 stays free, so philosopher 3 takes it and eats.

    lock ordering: every thread takes locks in one fixed order
    
    P4 needs forks 4 and 0: it takes 0 first (OSTEP Figure 31.16)
    
    fork 0  held by P0
    fork 1  held by P1
    fork 2  held by P2
    fork 3  held by P3
    fork 4  held by P3
    eating: P3   P4 holds nothing, so it blocks nobody
    
    a runnable version with pthread mutexes as forks (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <stdio.h>
    
    #define N 5
    #define MEALS 10000
    static pthread_mutex_t fork_[N];
    static int meals[N];
    
    static void *philosopher(void *arg) {
        int p = *(int *)arg;
        int l = p, r = (p + 1) % N;
        int first = l < r ? l : r, second = l < r ? r : l; /* lower first */
        for (int m = 0; m < MEALS; m++) {
            pthread_mutex_lock(&fork_[first]);
            pthread_mutex_lock(&fork_[second]);
            meals[p]++;                                      /* eat */
            pthread_mutex_unlock(&fork_[second]);
            pthread_mutex_unlock(&fork_[first]);
        }
        return NULL;
    }
    
    int main(void) {
        pthread_t t[N];
        int id[N];
        for (int i = 0; i < N; i++) pthread_mutex_init(&fork_[i], NULL);
        for (int i = 0; i < N; i++) {
            id[i] = i;
            pthread_create(&t[i], NULL, philosopher, &id[i]);
        }
        for (int i = 0; i < N; i++) pthread_join(t[i], NULL);
        for (int i = 0; i < N; i++) printf("%d ", meals[i]);
        printf("\n");
        return 0;
    }
    
    prints   10000 10000 10000 10000 10000   (it always finishes)
  11. Three patterns, one toolbox

    Each problem stands for a real pattern: a queue between threads, data read far more often than written, and several locks taken together. Counting semaphores, a reader count and one fixed lock order solve them.

    the bounded buffer with real Python threads:
    
    import threading
    
    SLOTS = 3
    buf = [None] * SLOTS
    empty = threading.Semaphore(SLOTS)  # free slots
    full = threading.Semaphore(0)       # filled slots
    mutex = threading.Lock()
    got = []
    
    def producer(items):
        for i, item in enumerate(items):
            empty.acquire()               # sleeps while the buffer is full
            with mutex:
                buf[i % SLOTS] = item
            full.release()
    
    def consumer(n):
        for i in range(n):
            full.acquire()                # sleeps while the buffer is empty
            with mutex:
                got.append(buf[i % SLOTS])
            empty.release()
    
    items = "ABCDEFGH"
    threads = [threading.Thread(target=producer, args=(items,)),
               threading.Thread(target=consumer, args=(len(items),))]
    for t in threads: t.start()
    for t in threads: t.join()
    print("".join(got))
    
    prints
    ABCDEFGH

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