kdp20260218-1
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| kdp20260218-1 [May 13, 2026 at 18:21] – yanevskiv | kdp20260218-1 [May 14, 2026 at 11:38] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | # KDP Exam (2026-02-18) Question 1 | ||
| + | Solve the dining philsophers problem by using *signal and continue* monitor discipline and by using *covering condition* technique. Ensure philosphers start eating in the order of their arrival. | ||
| + | ## Solution | ||
| + | ```c | ||
| + | #define N 5 /* number of philosophers */ | ||
| + | |||
| + | monitor DiningPhilosophers { | ||
| + | enum { THINKING, HUNGRY, EATING }; | ||
| + | int phil[N]; | ||
| + | cond delay[N]; | ||
| + | queue< | ||
| + | | ||
| + | bool canEat(int id) { | ||
| + | return (phil[(id - 1 + N) % N] != EATING) && (phil[(id + 1) % N] != EATING) | ||
| + | } | ||
| + | | ||
| + | void pickup(int id) { | ||
| + | phil[id] = HUNGRY; | ||
| + | queue.push(id); | ||
| + | while (q.front() != id || ! canEat(id)) | ||
| + | delay[id].wait(); | ||
| + | q.pop(); | ||
| + | phil[id] = EATING; | ||
| + | } | ||
| + | | ||
| + | void putdown(int id) { | ||
| + | phil[id] = THINKING; | ||
| + | for (int i = 0; i < N; i += 1) | ||
| + | delay[i].signal(); | ||
| + | } | ||
| + | } | ||
| + | ``` | ||
