more: Jollen 的 Embedded Linux 教育訓練

« Linux 的 Virtual Memory Areas(VMA):Process 與 VMA 整體觀念 | Home | Embedded Linux 測試:Bootstrap root filesystem(x86)階段《程式執行測試》 »

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。

--jollen

引用通告

如果您想引用這篇文章到您的Blog,
請複製下面的鏈接,並放置到您發表文章的相應界面中。

http://blog.jollen.org/mt-tb.cgi/330

發表一個評論

(您發表的意見將被立即接受,但需要一點時間與後端伺服器做同步,您的留言才會顯示在網站上。為避免 spam 攻撃,按「發表」後請輸入帳號密碼。使用者帳號:「nospam」、密碼:「nospam」。)

Top | 授權條款 | Jollen's Forum: Blog 評論、討論與搜尋
Copyright(c) 2006 www.jollen.org