看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux + raspberry pi 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) pthread ? 問題(Question): 其實是想問 我有3個thread(都是while loop)在跑,每個thread都要讀取i2c(系統只有一個) (每個thread每讀取一次都會sleep 4-25ms,不會有系統太繁忙的問題) (因為每個thread讀取的數據不一樣,分別需要200-500us從i2c傳數據過來) 我希望thread在讀取的時候不要被別的thread插進來 這個時候用mutex lock會比較好嗎? 還是我設個static變數: static int stat = 0; // 表示i2c狀態,1=使用中 0=閒置 void thread_1() { while (1) { while (stat !=0) usleep(1000); stat = 1; // 讀取資料.... stat = 0; usleep(4000); } } void thread_2() { while (1) { while (stat !=0) usleep(1000); stat = 1; // 讀取資料.... stat = 0; usleep(8000); } } 這樣的作法安全嗎?跟mutex比起來是不是比較快? 感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.214.241 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1446318563.A.F73.html ※ 編輯: wtchen (90.41.214.241), 11/01/2015 03:24:03 ※ 編輯: wtchen (90.41.214.241), 11/01/2015 03:24:22
LiloHuang: 你需要的是 pthread_spin_lock http://goo.gl/iiJ9S1 11/01 03:25
wtchen: spin_lock我看資料說單CPU不適合(我用RPi) 11/01 03:28
LiloHuang: 你現在的程式碼就是類似於多了 usleep 的 spin lock 11/01 04:21
LiloHuang: 但是還少了 atomic test-and-set operation 的部分 11/01 04:23
LiloHuang: 可以參考 std::atomic_flag http://goo.gl/MoNxRm 11/01 04:24
LiloHuang: 至於你提到在 RPi 上面跑,如果是單核心上就不需要了 11/01 04:30
LiloHuang: 建議可以把 usleep 改成 sched_yield(); 會較有效率 11/01 04:35
wtchen: 感謝,第一次聽到sched_yield 11/01 04:41