Try   HackMD

2024q1 第 13 週測驗題

目的: 檢驗學員對 Atomics 操作, Ring buffer, futex, mmap 的認知

作答表單: 測驗 1-2 (針對 Linux 核心「設計/實作」課程)

測驗 1

spms 是個使用 C11 撰寫的單一發布者多訂閱者 (Pub/Sub模型,參見 Build a one-to-many Pub/Sub system) 環狀緩衝區,適用於共享記憶體。發布者在不知道訂閱者的情況下,將訊息寫入環狀緩衝區,當訂閱者讀取一條訊息時,該訊息不會從環狀緩衝區中移除,其他訂閱者仍然可讀取。若訂閱者的讀取速度不夠快,它將錯過一些訊息。

系統設計入門:Pub/Sub Pattern

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

測試方式:

  • 在一個終端機執行: ./test pub 作為發布者
  • 在另一個終端機執行: ./test sub 作為訂閱者

原始程式碼

編譯方式

$ gcc -Wall -O2 -o test test.c spms.c -lrt -lpthread

參考輸出:

Msg: This is a key message
Msg: Msg: Thu May 16 18:49:11 2024
Msg: Msg: Thu May 16 18:49:12 2024
Msg: Msg: Thu May 16 18:49:13 2024
Msg: Msg: Thu May 16 18:49:14 2024
Msg: Msg: Thu May 16 18:49:15 2024
Msg: Msg: Thu May 16 18:49:20 2024
Msg: Msg: Thu May 16 18:49:21 2024
Msg: Msg: Thu May 16 18:49:22 2024

目前的 ring buffer 是 blocking,意味著當緩衝區是空的時候,讀取端會等到有資料為止。

作答規範: