kdp20260110-1
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| kdp20260110-1 [May 13, 2026 at 17:56] – yanevskiv | kdp20260110-1 [May 14, 2026 at 11:38] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | # KDP Midterm (2026-01-10) Question 1 | ||
| + | Write and explain the *Fine grain ticket algorithm* implemented with $\text{FA}$ opeartion. If we replaced $\text{FA}$ with $\text{TS}$ (test-and-set) operation implemented in the following way, would it be possible to implement a fine-grained solution? If yes, implement it. Is the critical section entry fair? Why / why not? | ||
| + | ```c | ||
| + | bool TS(bool lock) | ||
| + | { | ||
| + | atomic { | ||
| + | bool initial = lock; | ||
| + | lock = true; | ||
| + | return initial; | ||
| + | } | ||
| + | } | ||
| + | ``` | ||
| + | ## Solution | ||
| + | $\text{FA}$ operation stands for " | ||
| + | ```c | ||
| + | int FA(int& var, int by) | ||
| + | { | ||
| + | atomic { | ||
| + | int old = var; | ||
| + | var += by; | ||
| + | return old; | ||
| + | } | ||
| + | } | ||
| + | ``` | ||
| + | |||
| + | Fine-grained ticket algorithm implements " | ||
| + | ```c | ||
| + | #define N 5 /* Number of threads */ | ||
| + | |||
| + | shared int ticket = 0; | ||
| + | |||
| + | void thread(int id) | ||
| + | { | ||
| + | while (true) { | ||
| + | // lock | ||
| + | int number = FA(ticket, 1); | ||
| + | while (number != ticket) | ||
| + | skip(); | ||
| + | | ||
| + | // ... critical section ... | ||
| + | | ||
| + | // unlock | ||
| + | tikcet += 1; | ||
| + | } | ||
| + | } | ||
| + | ``` | ||
| + | |||
| + | The following is a *fine grain critical section* using $\text{TS}$. It's called " | ||
| + | ```c | ||
| + | #define N 5 /* number of threads */ | ||
| + | |||
| + | shared bool lock = false; | ||
| + | |||
| + | void thread(int id) | ||
| + | { | ||
| + | while (true) { | ||
| + | // lock | ||
| + | do { | ||
| + | while (lock) | ||
| + | skip(); | ||
| + | } while (!TS(lock)); | ||
| + | | ||
| + | // ... critical section ... | ||
| + | | ||
| + | // unlock | ||
| + | lock = false; | ||
| + | } | ||
| + | } | ||
| + | ``` | ||
