jollen.org

Jollen 的 Blog
Jollen's email: jollen # jollen.org
more:  Jollen's Training

Shared Memory 的 Race Condition

.作者:jollen/
.日期:January 16, 2007 3:54 PM


今天在討論基本的 shared memory 機制時聊到,shared memory 有同步性的問題(synchronization),主要的原因是 Linux 並未對 shared memory 做同步的控制。以下單純由 user-space programming 的角度來探討此觀念。

首先,試作以下 3 個小程式:

  • shm_allocate.c,用來請求 shared memory

  • shm_read.c,用來讀取 shared memory

  • shm_write.c,用來寫入 shared memory

以上程式可由 [http://tw.jollen.org/ipc-programming/shm_race.tar.bz2] 下載。以下是操作方法:

# ./shm_allocate jollen
Shared Memory Segment ID: 98306

先執行 shm_allocate 配置 shared memory,並任意填入一個初始字串,程式會印出此 shared memory 的 Segment ID。接著:

# ./shm_read 98306
Message of Shared Memory: jollen
Message of Shared Memory: jollen
Message of Shared Memory: jollen
Message of Shared Memory: jollen
...

再執行 shm_read,命令列參數加上 shared memory 的 Segment ID。shm_read 會持續不斷的讀取 shared memory 的內容。然後,在另一個 terminal 執行 shared memory 的寫入程式。

我們透過 shm_write 寫入 [00000000,11111111,22222222,...,99999999] 字串到 shared memory,並觀察輸出。由於 shm_write 寫入 shared memory 的資料是「相同數字的字串」,因此,若觀察到以下的結果,表示 shm_readshm_write 間存在 race condition 問題:

...
Message of Shared Memory: 98888888
Message of Shared Memory: 33333322
Message of Shared Memory: 11111111
Message of Shared Memory: 66666666
Message of Shared Memory: 44443333
Message of Shared Memory: 77777666
...

因此,使用 shared memory 做為 IPC 機制時,必須實作同步的演算法。由演算法層面來討論,我們區分以下 3 個層面的探討:

  • All Read:不需考慮 race condition。

  • 1-Write、n-Read(n >= 1)

  • n-Write、n-Read(n >= 1)

可此可知,當「只有有人寫入 shared memory,便要考慮 race conditon 問題」。若由演算法層面來思考此問題,以下是相對較為單純簡單的做法:

  • 1-Write、n-Read(n >= 1):可使用 lock file 的機制。

  • n-Write、n-Read(n >= 1):lock file 若是以 polling 方式做 waiting,必須配合 queue(或 circular queue)來實作,才能真正有效解決問題。

有機會的話,再跟大家分享朋友寫的 code。

Tags:

純手工打造說明:技術專欄文章為 Jollen 原創,內容皆為人工撰寫,無 AI 生成。轉載請註明出處與作者,並全文引用。轉載時請在文章開頭或結尾明顯處註明「本文出處:https://www.jollen.org,已取得原作者同意並授權使用。」
訂閱電子報:不定期 Jollen's Blog 精選文章隨 Moko365 電子報寄送;請透過 Moko365 電子報訂閱(可隨時取消)。

Copyright(c) 2001–2007 www.jollen.org. All rights reserved.
Last update: 2026-07-22