#6-1 作業系統
產生Race Condition的原因:多個process共享同個資源 & Context Switch
Race Condition的定義:因為process的執行順序不同,而造成結果不同
範例1
Context Switch 造成執行順序不同(情況1 & 情況2)
情況1Process1:Load x
Process1:Add 1
Process2:Load x
Process2:Add 2
Process2:Store x
Process1:Store x
-> x = 4
情況2Process1:Load x
Process1:Add 1
Process2:Load x
Process2:Add 2
Process1:Store x
Process2:Store x
-> x = 5
但正常來講 x 應該要是 6
範例2
Producer Consumer
Producer:只負責生產資料
Consumer:只負責拿出資料
-> 共享 1 個 buffer (緩衝區)
初始
#define BUFFER_SIZE 6
typedef struct {
...
} item;item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
Producer Process
//產生一個item,並放進bufferitem next_produced;while(true){ while( ((in+1) % BUFFER_SIZE) == out){
//do nothing
//因為buffer已經滿了
} buffer[in] = next_produced;
//把新產生item 放進去buffer in = (in + 1) % BUFFER_SIZE;
//in指到下一個位子
}
Consumer Process
//從buffer裡面,拿出一個itemitem next_consumed;while(true){
while( in == out){
//do nothing
//因為buffer是空的
}next_consumed = buffer[out];
//把拿出來的item 存到next_consumed裡
out = (out + 1) % BUFFER_SIZE;
//out指到下一個位子
}
為了判斷buffer是否滿了
需要有一個空格
當 (in+1) % BUFFER_SIZE) == out
代表buffer已經滿了
所以能放item的數量 = BUFFER_SIZE-1
buffer為空: in == out
buffer滿了: (in+1) % BUFFER_SIZE) == out
— — — — — — — — — — — — — — — — — — — — — — — — — —
我們希望能放的item數量 = BUFFER_SIZE
所以,新增一個變數 count
Producer Process
//只有在最後一行,加上count++;
//產生一個item,並放進bufferitem next_produced;while(true){ while( count == BUFFER_SIZE){
//do nothing
} buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
Consumer Process
//只有在最後一行,加上count--;
//從buffer裡面,拿出一個itemitem next_consumed;while(true){
while( count == 0){
//do nothing;
} next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
}
情況1Producer: register1 = count
Producer: register1 = register1 + 1
Consumer:register2 = count
Consumer:register2 = register2–1
Producer: count = register1
Consumer:count = register2
-> count = register2
情況2Producer: register1 = count
Producer: register1 = register1 + 1
Consumer:register2 = count
Consumer:register2 = register2–1
Consumer:count = register2
Producer: count = register1
-> count = register1
— — — — — — — — — — — — — — — — — — — — — — — — — —
現在你應該要知道
什麼是Race Condition?
並且可以舉出例子~
今天就先這樣吧~
下一篇再見 🥴