Cocos2d-x——pthread的使用注意事项

1:多线程所调用的成员方法定义为static。多线程

2:互斥锁(pthread_mutex_t)定义在cpp文件的开头,而且也定义为static。线程

3:pthread_mutex_init方法尽可能在最先的时候进行调用初始化(绝对不要在初始化以后当即开始新线程,不然pthread_mutex_lock极可能会返回22的错误,由于此时互斥量尚未初始化完成)。it

4:pthread_mutex_destroy方法尽可能在最晚的匹配的时候调用(好比构造析构——配对)。thread

 

代码:方法

头文件static

public:
pthread_t tid1;
pthread_t tid2;文件

static void* anotherTest1(void* args);
static void* anotherTest2(void* args);错误

类文件:return

static pthread_mutex_t mylock1;void

HelloWorld::HelloWorld()
{
  pthread_mutex_init(&mylock1, NULL);
}

HelloWorld::~HelloWorld()
{
  pthread_mutex_destroy(&mylock1);
}

void* HelloWorld::anotherTest1(void* args)
{
  int intResult1 = pthread_mutex_lock(&mylock1);
  CCLOG("Result1:%d", intResult1);

  for(int i=0;i<=10; i++) {
    CCLOG("1-%d",i);
    //sleep(1);
  }

  pthread_mutex_unlock(&mylock1);
  return NULL;
}

void* HelloWorld::anotherTest2(void* args)
{
  int intResult2 = pthread_mutex_lock(&mylock1);
  CCLOG("Result2:%d", intResult2);

  for(int j=0;j<=10; j++) {
    CCLOG("2-%d",j);
    //sleep(1);
  }

pthread_mutex_unlock(&mylock1);
  return NULL;
}

void HelloWorld::menuStartNewThread(CCObject* pSender){   pthread_create(&tid1, NULL, anotherTest1, NULL);   pthread_create(&tid2, NULL, anotherTest2, NULL);}

相关文章
相关标签/搜索