contributed by <RoyWFHuang>
futex(fast user-space locking), 用來減少 user space 使用競爭資源時, 對於 lock 的 kernel 系統呼叫.
舉例來說, 兩個 process, 一個是網路程式, 另一個是檔案 io 操作.
P1: socket 使用 write 動作時候, 會對於 buffer 做一次的 lock.
P2: fd write 對於 disk block 進行 io, 此時也會對 kernel 呼叫一次 lock
但兩個 processes 資源是沒有衝突的, 所以 lock 就變成是多餘的 kernel lock.
而 futex 提供一個簡易的 atomic 操作(利用 mmaps 讓 user space 操作使用同一個資源), 進入 futex lock 跟 unlock 時, 確認共享的資源變動前後是否一致, 如果一致則沒有發生競爭, 避免進行 system call ( futex(2) ), 如果衝突了, 則呼叫 futex_wait/ futex_wake 進行等待跟喚醒.
futex_op :
FUTEX_WAIT: 對應至 futex_wait
FUTEX_WAKE: 對應至 futex_wake
src code: github
目標: 使用 futex 包裝的 muthex.h 取代 POSIX thread.
target | replace by |
---|---|
pthread_mutex_init | mutex_init |
pthread_mutex_destory | (removed)* |
pthread_mutex_lock | mutex_lock |
pthread_mutex_unlock | mutex_unlock |
pthread_cond_init | cond_init |
pthread_cond_destory | (removed)* |
pthread_cond_signal | cond_signal |
*pthread_mutex_destory/pthread_cond_destory remove: 因為 mutex/cond init 使用 atomic init 去設定 mutex state, 沒有使用到 POSIX thread system call, 所以不需要其他相對應的回收動作.
測試結果:
若使用程式內預設的
在競爭比較不激烈( thread nunber, element 數量較少)的狀況下, 符合預期.
但在許多 thread 共同競爭下, futex 似乎就沒有 pthread 效能來的好?
或許是如同 futex 使用上所說, 如果 thread 之間, 競爭的資源越不相關, 使用的成本則是會越低?
首先先看 POSIX thread 提供的 API
pthread_attr_set(get)schedpolicy(3):
pthread_attr_setinheritsched(3)
test reusult using pthread define.
使用原本 linux 內的 futex (未經改寫)
很明顯的看出 mid priroity 提早在 high priority 之前跑完了.
其中
另外從 fetex(2) 文件中閱讀:
上述幾點得知, futex status 如果為 0, 則可以用 atomic instruction 去改變內容, 如果不為 0, 則使用 FUTEX_LOCK_PI or FUTEX_LOCK_PI2 去等待 release.
另外一點很重要: 必須使用 TID 不可以使用 pthread id 下面就是用 thread id 跑出來的結果
會連基本的正確性都有問題…
改用 tid 之後結果就跟 pthread 結果一致了 src code
fetex(2)
並行程式設計: 建立相容於 POSIX Thread 的實作
Linux中的同步机制 – Futex
蜗窝科技 - futex基础问答
openeuler - linux–futex原理分析