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


1:多線程所調用的成員方法定義為static。

2:互斥鎖(pthread_mutex_t)定義在cpp文件的開頭,並且也定義為static。

3:pthread_mutex_init方法盡量在最早的時候進行調用初始化(絕對不要在初始化之后立即開始新線程,否則pthread_mutex_lock很可能會返回22的錯誤,因為此時互斥量還沒有初始化完成)。

4:pthread_mutex_destroy方法盡量在最晚的匹配的時候調用(比如構造析構——配對)。

 

代碼:

頭文件

public:
pthread_t tid1;
pthread_t tid2;

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

類文件:

static pthread_mutex_t mylock1;

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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM