Sitemap
ExcitedMail

ExcitedMail

Synchronization

6 min readMar 5, 2025

如何解決 race condition?回到單子上寫數字的那個情況,如果你在得知數字、寫數字貼上去之前,確保這中間不會有任何人更改數字,就能保證你更新前後如同預期。另一個人也只會在之後看到數字才寫新的數字上去,就能保證你們兩個分別想增加的數字都能確實地被加上上去。

Get ExcitedMail’s stories in your inbox

Join Medium for free to get updates from this writer.

概念上就是同步,在任何人想要對數字做點甚麼的時候,都能知道最新的狀況,這個機制就稱為 Synchronization。常見到的方式有底下幾種:

  • Mutex
    (對某個區段上鎖,此期間其餘 thread 不能執行需要鎖的區段)
  • Read-Write Lock
    (把鎖分為 read, write, write 的時候不允許有其他人正在持有任何 read, write lock)
  • Atomic Operations
    (確保指令執行過程中不被中斷,並且執行完後會寫回記憶體)
  • Semaphore
    (管理同時能執行區段的 thread 數量)
  • Barrier
    (確保同時有多個 thread 抵達 barrier 後才能繼續執行)

由於種類蠻多的,這邊介紹 mutex 以及 atomic operation。首先是 mutex,請看底下的範例:

#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 2
#define NUM_INCREMENTS 50000

// 共享變數
int counter = 0;

// 定義互斥鎖
pthread_mutex_t mutex;

// 執行緒函數,每個執行緒增加 counter 的值
void* increment_counter(void* arg) {
for (int i = 0; i < NUM_INCREMENTS; i++) {
// 加鎖,確保只有一個執行緒在修改 counter
pthread_mutex_lock(&mutex);

counter++; // 這裡不會有race condition了

// 解鎖,允許其他執行緒訪問 counter
pthread_mutex_unlock(&mutex);
}
return NULL;
}

int main() {
pthread_t threads[NUM_THREADS];

// 初始化互斥鎖
pthread_mutex_init(&mutex, NULL);

// 創建兩個執行緒
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_create(&threads[i], NULL, increment_counter, NULL)) {
printf("Error creating thread\n");
return 1;
}
}

// 等待所有執行緒結束
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_join(threads[i], NULL)) {
printf("Error joining thread\n");
return 1;
}
}

// 輸出結果
printf("Final counter value: %d\n", counter);

// 銷燬互斥鎖
pthread_mutex_destroy(&mutex);

return 0;
}

這種情況就不會發生 race condition,因為原本可能發生的情況是在兩個 thread 同時在執行 count++ 的過程中,由於沒有等對方執行完自己就執行其中的讀取操作之類的,所以如果我們保證了 count++ 的時候不會有他人同時執行這件事,就不會發生 race condition。

#include <stdio.h>
#include <pthread.h>
#include <stdatomic.h>

#define NUM_THREADS 2
#define NUM_INCREMENTS 1000

// 共享變數
atomic_int counter = 0;

// 執行緒函數,每個執行緒增加 counter 的值
void* increment_counter(void* arg) {
for (int i = 0; i < NUM_INCREMENTS; i++) {
atomic_fetch_add(&counter, 1); // 原子操作增加 counter
}
return NULL;
}

int main() {
pthread_t threads[NUM_THREADS];

// 創建兩個執行緒
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_create(&threads[i], NULL, increment_counter, NULL)) {
printf("Error creating thread\n");
return 1;
}
}

// 等待所有執行緒結束
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_join(threads[i], NULL)) {
printf("Error joining thread\n");
return 1;
}
}

// 輸出結果
printf("Final counter value: %d\n", counter);

return 0;
}

這個例子是利用 atomic operation,這種方法就需要 library 本身有支援需要的操作,通常只有較為簡單的操作會有這類的 operation,這邊就是使用了 atomic_fetch_add() 來保證 counter++ 的時候會完整執行完才讓其他 thread 執行。

兩者的方法不同,但都是保證 counter++ 的過程中不被中斷。 mutex 的做法可以廣泛用在更複雜的情境,保證某一段複雜的操作都不會被他人中斷。缺點是可能讓他人占用 CPU 時無法執行任何操作,浪費 CPU time。 atomic operation 的作法可以直接讓指令執行完畢才結束 CPU time,減少時間浪費。缺點是需要本身 library 支援該操作,並且通常只有簡單操作才會被支援。

抓兩個範例來講篇幅感覺差不多,如果想看看不同的方法用起來如何也可以留言跟我說,會好好解釋一遍的,掰啦。

--

--