//HelloWorld声明添加变量
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp,so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
virtual bool init();
void runStartMyThread();
void runStartMyThread2(); // a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
private:
int m_nStore = 50;
std::mutex m_mutex; ////互斥变量,用来锁定线程
};
#endif // __HELLOWORLD_SCENE_H__
void HelloWorld::runStartMyThread()
{
while (m_nStore > 0) {
m_mutex.lock();
CCLOG("%d",m_nStore);
--m_nStore;
m_mutex.unlock();
}
}
void HelloWorld::runStartMyThread2()
{
while (m_nStore > 0) {
m_mutex.lock();
CCLOG("%d",m_nStore);
--m_nStore;
m_mutex.unlock();
}
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
std::thread t(&HelloWorld::runStartMyThread,this);
//t.join(); 该函数表示等待执行完线程在执行主线程
t.detach();
std::thread t2(&HelloWorld::runStartMyThread2,0)"> //t.join();
t2.detach();
}
结果如下:
cocos2d: 50
cocos2d: 49
cocos2d: 48
cocos2d: 47
cocos2d: 46
cocos2d: 45
cocos2d: 44
cocos2d: 43
cocos2d: 42
cocos2d: 41
cocos2d: 40
cocos2d: 39
cocos2d: 38
cocos2d: 37
cocos2d: 36
cocos2d: 35
cocos2d: 34
cocos2d: 33
cocos2d: 32
cocos2d: 31
cocos2d: 30
cocos2d: 29
cocos2d: 28
cocos2d: 27
cocos2d: 26
cocos2d: 25
cocos2d: 24
cocos2d: 23
cocos2d: 22
cocos2d: 21
cocos2d: 20
cocos2d: 19
cocos2d: 18
cocos2d: 17
cocos2d: 16
cocos2d: 15
cocos2d: 14
cocos2d: 13
cocos2d: 12
cocos2d: 11
cocos2d: 10
cocos2d: 9
cocos2d: 8
cocos2d: 7
cocos2d: 6
cocos2d: 5
cocos2d: 4
cocos2d: 3
cocos2d: 2
cocos2d: 1
cocos2d: run in main thread