Table of Contents

KDP Midterm (2026-01-10) Question 2

Consider a dining table that can seat at most $N$ people ($N > 2$). A person may take some food, sit at the table (sitAtTable()), eat, leave the table (leaveTable()) and walk away. No person should eat alone i.e. sit at the table alone. Also, every person that takes food must necessarily sit down in order to eat. Create a solution for this probalom using a signal and wait monitor. The monitor should only have two methods sitAtTable() and leaveTable()

Solution

#define N ... /* N > 2 */
 
monitor Table {
    int count = 0;
    cond wantToSit;
    cond wantToLeave;
 
    void sitAtTable() {
        while (count == N)
            wantToSit.wait();
        count += 1;
        if (count == 1)
            wantToLeave.wait();
    }
 
    void leaveTable() {
        while (count == 2)
            wantToLeave.wait();
        count -= 1;
        if (count >= 2)
            wantToLeave.signal();
        wantToSit.signal();
    }
}