Synchronization Background
Introduction
Synchronization 處理多個 process / thread 共享資料時的 coordination,目標是避免 concurrent 或 parallel execution 讓 shared state 被不合法的 interleaving 破壞。
重點不是消除 concurrency,而是讓會改 shared data 的部分有可預期的執行順序。
Race Condition
Race condition 指多個 process 同時 access / manipulate 同一份 data,而最後結果取決於執行交錯順序。
count++ 看起來是一行,但實際可能是:
register1 = count;
register1 = register1 + 1;
count = register1;如果 count++ 與 count-- 交錯執行,最後值可能不是預期的原值。
只要 shared data 的 read-modify-write 不是 atomic,就可能需要 synchronization。