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中的代碼先一步結束。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章