有的时候很多操作如果在cocos2dx的主线程中来调用,可能会极大地占用主线程的时间,从而使游戏的不流畅。比如在获取网络文件数据或者在数据比较大的游戏存档时,就需要使用多线程了。
网上的一些教程上是使用pthread来创建新线程的,需要加入lib和头文件,但在cocos2dx 3.0中并未发现有pthread的支持文件,后来才发现在c++11中已经拥有了一个更好用的用于线程操作的类std::thread。cocos2dx 3.0的版本默认是在vs2012版本,支持c++11的新特性,使用std::thread来创建线程简直方便。
1. std::thread的一些使用方法。
需要加头文件 #include<thread>
直接调用函数
std::thread t(func);
std::thread t(func,param1,param2...);类的成员函数(函数类型不需要是静态的)
class MyClass { void func1(); void func2(int a,string b); } MyClass myclass; std::thread t1(&MyClass::func1,&myclass); std::thread t2(&MyClass::func2,&myclass,444,"this is a string"); t1.detach(); t2.join();
可以看出使用std::thread来创建线程十分的方便,而且可读性更好了,特别是在传参数这方面。
还有就是线程的互斥量std::mutex
std::mutex _mutex; void thread_fun1() { _mutex.lock();//加锁 ... _mutex.unlock();//解锁 } void thread_fun2() { std::lock_guard<std::mutex> lk(_mutex); //线程开始加锁,退出时自动解锁 ... }具体的互斥量使用好有很多,但太繁了(其实是看不懂),我只写点我用的到的。
1.std::thread 学习初步
2.C++11 thread
2.performFunctionInCocosThread()
在cocos2dx中使用多线程,难免要考虑线程安全的问题。cocos2dx 3.0中新加入了一个专门处理线程安全的函数performFunctionInCocosThread()。他是Scheduler类的一个成员函数:
void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function) /** calls a function on the cocos2d thread. Useful when you need to call a cocos2d function from another thread. This function is thread safe. @since v3.0 */在其他线程中控制主线程去调用一个函数,这个函数会是线程安全的。
具体定义:
void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function) { _performMutex.lock(); _functionsToPerform.push_back(function); _performMutex.unlock(); }
1.同步问题
因为使用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()); }
然后在cocos2dx中以这个函数创建一个线程,运行可以看到结果:
可以看出performFunctionInCocosThread中的代码执行完毕在 线程退出之后,所以在使用时可能要加入一些值判断代码是否已经运行完毕。2.互斥问题
如果在线程中要使用互斥,而又要使用performFunctionInCocosThread的话。我认为应该将performFunctionInCocosThread调用放到线程的最后,然后在performFunctionInCocosThread调用函数的末尾使用mutex.unlock(),这样才能确保互斥。
在自己的线程中对精灵的创建等操作可能会没有用,所有performFunctionInCocosThread还是很有用的。
cocos2dx的线程学习就到这了