作者wtchen (没有存在感的人)
看板C_and_CPP
标题[问题] 防止装置被2个以上的thread使用要用mutex
时间Sun Nov 1 03:09:20 2015
开发平台(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://webptt.com/cn.aspx?n=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
2F:→ wtchen: spin_lock我看资料说单CPU不适合(我用RPi) 11/01 03:28
3F:→ LiloHuang: 你现在的程式码就是类似於多了 usleep 的 spin lock 11/01 04:21
4F:→ LiloHuang: 但是还少了 atomic test-and-set operation 的部分 11/01 04:23
6F:推 LiloHuang: 至於你提到在 RPi 上面跑,如果是单核心上就不需要了 11/01 04:30
7F:→ LiloHuang: 建议可以把 usleep 改成 sched_yield(); 会较有效率 11/01 04:35
8F:→ wtchen: 感谢,第一次听到sched_yield 11/01 04:41