cocos2d-x:子线程中更新UI

直接在子线程中调用一下代码:

Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]
				{
					// 运行在主线程中
					log("performFunctionInCocosThread");
				});

需要注意的是,因为这段代码运行在主线程中,你无法知道具体运行的时间,有可能线程已经运行完毕退出了,这部分代码还没有执行完毕。所以需要自己把控。

使用:

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

class HelloWorld : public cocos2d::Scene
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();
    
    void menuCloseCallback(cocos2d::Ref* pSender);
	// 线程调用的方法
	void  runThread();
    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;
using namespace std;
Scene* HelloWorld::createScene()
{
	return HelloWorld::create();
}

Label* label;
bool HelloWorld::init()
{
	if (!Scene::init())
	{
		return false;
	}
	auto visibleSize = Director::getInstance()->getVisibleSize();
	// 文字标签
	label = Label::createWithSystemFont("1111111", "Arial", 25);
	label->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2));
	this->addChild(label);

	// 开启线程
	thread t1(&HelloWorld::runThread,this);
	t1.detach();
	return true;
}
// 线程调用的方法
void HelloWorld::runThread() {
	// 子线程中 调用 该方法
	Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]
	{
		for (size_t i = 0; i < 1000; i++)
		{
		}
		label->setString("22222222222222");

		log("mian  finish");
	});
	// 子线程退出
	log("thread finish");
}

开启一个线程,线程调用 runThread() 方法。

该方法中,在代用 performFunctionInCocosThread 方法,切换到主线程

打印日志可以看到:

子线程比 performFunctionInCocosThread中的代码先一步结束。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值