[問題] 防止裝置被2個以上的thread使用要用mutex

看板C_and_CPP (C/C++)作者 (沒有存在感的人)時間10年前 (2015/11/01 03:09), 10年前編輯推噓2(206)
留言8則, 2人參與, 最新討論串1/1
開發平台(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

11/01 03:25, , 1F
你需要的是 pthread_spin_lock http://goo.gl/iiJ9S1
11/01 03:25, 1F

11/01 03:28, , 2F
spin_lock我看資料說單CPU不適合(我用RPi)
11/01 03:28, 2F

11/01 04:21, , 3F
你現在的程式碼就是類似於多了 usleep 的 spin lock
11/01 04:21, 3F

11/01 04:23, , 4F
但是還少了 atomic test-and-set operation 的部分
11/01 04:23, 4F

11/01 04:24, , 5F
可以參考 std::atomic_flag http://goo.gl/MoNxRm
11/01 04:24, 5F

11/01 04:30, , 6F
至於你提到在 RPi 上面跑,如果是單核心上就不需要了
11/01 04:30, 6F

11/01 04:35, , 7F
建議可以把 usleep 改成 sched_yield(); 會較有效率
11/01 04:35, 7F

11/01 04:41, , 8F
感謝,第一次聽到sched_yield
11/01 04:41, 8F
文章代碼(AID): #1MDH7Zzp (C_and_CPP)
文章代碼(AID): #1MDH7Zzp (C_and_CPP)