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

转载于:https://www.cnblogs.com/leonbao/p/3148929.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值