Site Tools


kdp20260110-2

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
kdp20260110-2 [May 13, 2026 at 17:59] – created yanevskivkdp20260110-2 [May 14, 2026 at 11:38] (current) – external edit 127.0.0.1
Line 1: Line 1:
 +# 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
 +```c
 +#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();
 +    }
 +}
 +```