[問題] 防止裝置被2個以上的thread使用要用mutex
開發平台(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
11/01 03:25, 1F
→
11/01 03:28, , 2F
11/01 03:28, 2F
→
11/01 04:21, , 3F
11/01 04:21, 3F
→
11/01 04:23, , 4F
11/01 04:23, 4F
→
11/01 04:24, , 5F
11/01 04:24, 5F
推
11/01 04:30, , 6F
11/01 04:30, 6F
→
11/01 04:35, , 7F
11/01 04:35, 7F
→
11/01 04:41, , 8F
11/01 04:41, 8F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章