operating-systems concurrency

Definition

Bakery Algorithm

The Bakery algorithm, developed by Leslie Lamport, solves the mutual exclusion problem for processes. Each process takes a numbered ticket upon entering; the process with the smallest ticket enters the critical section first.

Algorithm

The algorithm maintains two shared arrays:

ArrayTypeMeaning
choosing[0..n-1]booleanchoosing[i] is true while process reads the maximum ticket number
number[0..n-1]integernumber[i] is the ticket held by process (0 means no ticket)
Void process(int i)
    while (true) {
        choosing[i] = true;
        number[i] = 1 + max(number[0], ..., number[n-1]);
        choosing[i] = false;
        
        for (int j = 0; j < n; j++) {
            while (choosing[j]) { /* wait */ }

            while (number[j] != 0 &&
                   (number[j], j) < (number[i], i)) {
                /* wait */
            }
        }
        
        /* --- Critical Section --- */
        
        number[i] = 0;
        
        /* --- Remainder Section --- */
    }

Lexicographic Ordering

Tickets are compared as pairs . If two processes obtain the same ticket number, the process with the smaller ID precedes the other. This ensures a total order among waiting processes.

Correctness

Mutual Exclusion

No two processes execute the critical section simultaneously.

and (with ) both enter the critical section. Both must have passed the inner while loop for each other. For to pass 's test, either number[j] == 0 or . For to pass 's test, either number[i] == 0 or . Since both hold non-zero tickets in the critical section, we have both and , a contradiction.

Suppose processes

Progress

If some process wishes to enter the critical section and no process is currently in it, some process will enter within finite time.

be the process with the smallest pair. For any other waiting process , we have . Thus will not block on any process. Process proceeds to the critical section.

Among processes waiting with non-zero tickets, let

Bounded Waiting

A process waiting to enter the critical section will enter within turns.

takes its ticket, any process that later takes a ticket receives (or equal with , giving priority). Process waits only for processes already holding tickets. At most such processes exist, and each enters the critical section exactly once before .

When process