cocos2dx3.3线程简单使用

cocos2dx3.3线程简单使用,第1张

概述// 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



//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

总结

以上是内存溢出为你收集整理的cocos2dx3.3线程简单使用全部内容,希望文章能够帮你解决cocos2dx3.3线程简单使用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1024769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存