合作行程可用 Producer-consumer 問題來闡述,Producer負責產生資訊,並由consumer使用。
假如我們要設計一個buffer在shared memory中讓生產者和消費者共享資料…
#define BUFFER SIZE 10
typedef struct {
. . .
} item;
// circular array
item buffer[BUFFER SIZE];
int in = 0; // in 指向buffer的下一個空位
int out = 0; // out 指向buffer第一個填滿的位置
int count = 0; // array有的item數量
item next_produced, next_consumed;
// Producer process
while (true)
{
/* produce an item in next produced */
while (count == BUFFER SIZE)
; /* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER SIZE;
count++;
}
// Consumer process
while (true)
{
while (count == 0)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER SIZE;
count--;
/* consume the item in next consumed */
}
count 可能因為生產者和消費者並行執行count++和count- -而不會是正確的值
count++ 在底層的機器指令可能為…
register1 = count
register1 = register1 +1
count = register1
count- -
register2 = count
register2 = register2 −1
count = register2