shihyu 发表于 2016-05-15 08:26

Liunx 線程交換打印訊息

本帖最后由 shihyu 于 2016-05-15 08:27 编辑



#include <android/sensor.h>
#include <gui/Sensor.h>
#include <gui/SensorManager.h>
#include <gui/SensorEventQueue.h>
#include <utils/Looper.h>
#include <pthread.h>
#include <unistd.h>

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

using namespace android;
static int g_Flag = 1;


void* thread2_fun(void* args) {

    while (1) {
      if (g_Flag != 1) {
            continue;
      }
      printf("thread2_fun g_Flag=%d, g_Flag addr=%p\n",
               g_Flag, &g_Flag);

      g_Flag = 2;
    }
}
   
void* thread1_fun(void* args)
{
    while (1) {
      if (g_Flag != 2) {
            continue;
      }
      printf("thread1_fun g_Flag=%d, g_Flag addr=%p\n",
               g_Flag, &g_Flag);

      g_Flag = 1;
    }
}

int main(int argc, char** argv)
{
    pthread_t thread1;
    pthread_t thread2;

    pthread_create(&thread1, NULL, thread1_fun, NULL);
    pthread_create(&thread2, NULL, thread2_fun, NULL);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}在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 做什么处理?

谢谢

hellioncu 发表于 2016-05-15 20:40

g_Flag前加个volatile修饰试试
页: [1]
查看完整版本: Liunx 線程交換打印訊息