免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1970 | 回复: 1

[其他] Liunx 線程交換打印訊息 [复制链接]

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:49:03
发表于 2016-05-15 08:26 |显示全部楼层
本帖最后由 shihyu 于 2016-05-15 08:27 编辑


  1. #include <android/sensor.h>
  2. #include <gui/Sensor.h>
  3. #include <gui/SensorManager.h>
  4. #include <gui/SensorEventQueue.h>
  5. #include <utils/Looper.h>
  6. #include <pthread.h>
  7. #include <unistd.h>

  8. #include <sys/syscall.h>
  9. #define gettid() syscall(__NR_gettid)

  10. using namespace android;
  11. static int g_Flag = 1;


  12. void* thread2_fun(void* args) {

  13.     while (1) {
  14.         if (g_Flag != 1) {
  15.             continue;
  16.         }
  17.         printf("thread2_fun g_Flag=%d, g_Flag addr=%p\n",
  18.                g_Flag, &g_Flag);

  19.         g_Flag = 2;
  20.     }
  21. }
  22.    
  23. void* thread1_fun(void* args)
  24. {
  25.     while (1) {
  26.         if (g_Flag != 2) {
  27.             continue;
  28.         }
  29.         printf("thread1_fun g_Flag=%d, g_Flag addr=%p\n",
  30.                g_Flag, &g_Flag);

  31.         g_Flag = 1;
  32.     }
  33. }

  34. int main(int argc, char** argv)
  35. {
  36.     pthread_t thread1;
  37.     pthread_t thread2;

  38.     pthread_create(&thread1, NULL, thread1_fun, NULL);
  39.     pthread_create(&thread2, NULL, thread2_fun, NULL);

  40.     pthread_join(thread1, NULL);
  41.     pthread_join(thread2, NULL);
  42.     return 0;
  43. }
复制代码
在linux 上正常不断交错打印下面这两行
thread2_fun g_Flag=1, g_Flag addr=0x557a133008
thread1_fun g_Flag=2, g_Flag addr=0x557a133008



但android 手机上跑这两thread无法用g_Flag控制交错打印讯息
只印出就下面两行没了
thread2_fun g_Flag=1, g_Flag addr=0x557a133008
thread1_fun g_Flag=2, g_Flag addr=0x557a133008



我没使用sleep 也没 block 问题, 就是g_Flag

没成立就一直在绕回圈 , 一直想不明白会什么只能印这两行就没了

请问这可能是什么原因? 还是android 上 while 空转会造成 cpu busy ,

kernel 会对这两个thread 做什么处理?

谢谢

论坛徽章:
323
射手座
日期:2013-08-23 12:04:38射手座
日期:2013-08-23 16:18:12未羊
日期:2013-08-30 14:33:15水瓶座
日期:2013-09-02 16:44:31摩羯座
日期:2013-09-25 09:33:52双子座
日期:2013-09-26 12:21:10金牛座
日期:2013-10-14 09:08:49申猴
日期:2013-10-16 13:09:43子鼠
日期:2013-10-17 23:23:19射手座
日期:2013-10-18 13:00:27金牛座
日期:2013-10-18 15:47:57午马
日期:2013-10-18 21:43:38
发表于 2016-05-15 20:40 |显示全部楼层
g_Flag前加个volatile修饰试试
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP