作業系統›Ch6 行程同步(Process Synchronization)
第 8 題/共 32 題
◀ OS 8/32
8. Spin Lock、Test-And-Set、Compare-And-Swap、Load-Linked/Store-Conditional、Fetch-And-Add
#OS-06-008中Spin LockTest-And-SetCompare-And-SwapLoad-Linked/Store-ConditionalFetch-And-Add

The spin lock ensures the correctness of concurrent programs on multiple processors. Please choose the correct spin-lock implementation(s) and usage(s) including the Test-And-Set, Compare-And-Swap, Load-Linked and Store-Conditional, and Fetch-And-Add instructions. (Note that the LoadLinked() and StoreConditional(), respectively, perform Load-Linked and Store-Conditional operations).

(a)

int TestAndSet(int *old_ptr, int new) {
    int old = *old_ptr;
    *old_ptr = new;
    return old;
}

(b)

int CompareAndSwap(int *ptr, int expected, int new) {
    int original = expected;
    if (*ptr == expected)
        original = new;
    return original;
}

(c)

void lock(lock_t *lock) {
    while (1) {
        if (LoadLinked(&lock->flag) == 1) return;
        while (StoreConditional(&lock->flag, 1) == 1);
    }
}

(d)

int FetchAndAdd(int *ptr) {
    int old = *ptr;
    *ptr = old + 1;
    return *ptr;
}
📄 交大115
跳轉到第題
▤完整推導請見《WH 資工筆記 · 作業系統》Ch6 行程同步(Process Synchronization)
本章題號 · 1–20 / 32