---
tags: linux2024
---
# [2024q1](https://wiki.csie.ncku.edu.tw/linux/schedule) 第 15 週測驗題
:::info
目的: 檢驗學員對[並行和多執行緒程式設計](https://hackmd.io/@sysprog/concurrency)的認知
:::
==[作答表單](https://docs.google.com/forms/d/e/1FAIpQLSeD8AXS-ig9Z_oC82U94-fm16GmoqOx2Gmlk0vST5VbHbp7MA/viewform)==
### 測驗 `1`
考慮我們嘗試建構 lock-free 的 MPMC broadcast queue、依循 [Publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) 模式,程式碼可見 [broadcast](https://gist.github.com/jserv/097c58737b3b87c1e72c8938d2b3b5a2),其中 `pool.[ch]` 是 lock-free memory pool。
編譯方式:
```shell
$ gcc -Wall -O2 -D_GNU_SOURCE \
-o stress \
stress.c \
broadcast.c \
pool.c \
-lpthread
```
參考執行輸出:
```
Test: 1pub0sub
Pub Thread 0 | n_msgs: 100000 n_drops: 0 | 169 ns/msg
Test: 2pub0sub
Pub Thread 0 | n_msgs: 100000 n_drops: 0 | 519 ns/msg
Pub Thread 1 | n_msgs: 100000 n_drops: 0 | 416 ns/msg
Test: 4pub0sub
Pub Thread 0 | n_msgs: 100000 n_drops: 0 | 945 ns/msg
Pub Thread 1 | n_msgs: 100000 n_drops: 0 | 965 ns/msg
Pub Thread 2 | n_msgs: 100000 n_drops: 0 | 952 ns/msg
Pub Thread 3 | n_msgs: 100000 n_drops: 0 | 967 ns/msg
Test: 4pub0sub
Pub Thread 0 | n_msgs: 100000 n_drops: 0 | 2800 ns/msg
Pub Thread 1 | n_msgs: 100000 n_drops: 0 | 3015 ns/msg
Pub Thread 2 | n_msgs: 100000 n_drops: 0 | 3065 ns/msg
Pub Thread 3 | n_msgs: 100000 n_drops: 0 | 3060 ns/msg
Pub Thread 4 | n_msgs: 100000 n_drops: 0 | 3062 ns/msg
Pub Thread 5 | n_msgs: 100000 n_drops: 0 | 3033 ns/msg
Pub Thread 6 | n_msgs: 100000 n_drops: 0 | 3021 ns/msg
Pub Thread 7 | n_msgs: 100000 n_drops: 0 | 3043 ns/msg
```
AAAA, BBBB, CCCC, DDDD, EEEE, FFFF 皆為變數名稱