Atomic Variable

Introduction

Atomic variable 是建立在 atomic hardware instruction 上的 higher-level tool,提供 integer、boolean 等基本型別的 atomic operation。

它適合 atomic counter、sequence number 這類單一 shared variable update。

How it works?

Atomic increment 可用 CAS retry 實作:

void increment(atomic_int *v) {
    int temp;
    do {
        temp = *v;
    } while (temp != compare_and_swap(v, temp, temp + 1));
}

若中途其他 thread 改過 v,CAS 失敗,重新讀取並再試一次。

Limitation

Atomic variable 只保證單一變數的 update 是 atomic,不保證整個 protocol 正確。

例如 bounded buffer 不只需要 atomic count++,還要保證「檢查 count、存取 buffer、更新 count」這一整段順序正確,所以仍可能需要 semaphore 或 lock。