在使用多线程时,总会遇到线程安全的问题。cocos2dx 3.0系列中新加入了一个专门处理线程安全的函数performFunctionInCocosThread(),他是Scheduler类的一个成员函数:
void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function)
当在其他线程中调用cocos2d的函数时使用该函数。
使用这个函数就能安全的在其他线程中去控制cocos2dx的一些操作了。比如在worker线程中对精灵的创建等操作可能会没有用,在performFunctionInCocosThread就能很容易实现。
比如:
void thread_fun()
{
log("new thread create:t_id:0x%x",GetCurrentThreadId());
Director::getInstance()->getScheduler()->performFunctionInCocosThread([&,this]
{
for(int i=0;i<=1000;i++){}
log("[performFunctionInCocosThread] finished!");
});
log("thread finished:t_id:0x%x",GetCurrentThreadId());
}
这时会看到一个问题,线程结束后performFunctionInCocosThread中运行的代码才结束,这是因为使用performFunctionInCocosThread将参数函数中的代码放到主线程中去运行,所以就无法知道运行完这段代码需要多少时间。
Cocos2d-X多线程(3) cocos2dx中的线程安全
最新推荐文章于 2021-12-20 00:00:00 发布