(a) (8 pt) Suppose N processes with IDs 0, 1, 2, …, N − 1 need to share some critical region of code, which only one at a time is allowed to execute, and where they are required to repeatedly cycle through this section in the natural order (0, 1, 2, …, N − 1). If turn is a shared integer variable initialized to zero, and current_pid is the ID of the currently executing process, and each executes the following pseudo-code, could a race condition occur? Why or why not? Be precise.
while(TRUE)
{
while(turn != current_pid); /* wait */
critical_region();
turn = (turn + 1) % N;
noncritical_region();
}
(b) (8 pt) How many semaphores would be required if a semaphore solution to this problem was used instead? Write some pseudo-code for this.
(a) 不會有 race condition
共用變數只有 turn,而會寫 turn 的只有「turn == current_pid」的那一個 process;其他 process 都卡在 while 裡,只讀不寫
所以任何時刻最多一個 process 能通過 while 進 critical region,它離開時才把 turn 改成下一個 ID → mutual exclusion 成立,順序也固定是 \(0,1,\dots,N-1\)
前提是對 int 的讀寫是 atomic。代價:輪到 \(i\) 但 \(i\) 還在 noncritical region 或根本不想進來時,其他人想進也進不去(progress 不成立),而且全程 busy waiting 浪費 CPU;不過這題要的就是固定輪流的順序
(b) 需要 \(N\) 個 semaphore,每個 process 一個;s[0] 初值 1,其餘初值 0
semaphore s[N]; // s[0] = 1, s[1..N-1] = 0
// process i
while (TRUE) {
wait(s[i]); // 等上一個人交棒
critical_region();
signal(s[(i + 1) % N]); // 交棒給下一個
noncritical_region();
}
一開始只有 s[0] 是 1,所以只有 process 0 能進;它做完 signal(s[1]),process 1 才能進,依序繞回 0
任何時刻 \(N\) 個 semaphore 的值加起來最多是 1,所以 mutual exclusion 成立;跟 (a) 比,等待的 process 是 block 住,不再 busy waiting
(a) 不會 (b) \(N\) 個 semaphore(初值 1,0,…,0),process \(i\) 先 wait(s[i])、離開時 signal(s[(i+1) mod N])