事实上在cocos2dx下使用多线程事实上就是用C++去写,这里提供几个简单的样例:
原文地址:http://blog.youkuaiyun.com/qqmcy/article/details/36227377
1、
//
// PublicScene.cpp
// testthirdone
//
// Created by 杜甲 on 14-7-1.
//
void hello()
{
log("hello thread");
}
bool PublicScene::init()
{
bool bRet = false;
do {
CC_BREAK_IF(!Scene::init());
std::thread t1(hello);
t1.join();
log("主线程");
bRet = true;
} while (0);
return bRet;
}
std::thread t1(hello);
t1.join();
log("主线程");
2、
//
// PublicScene.cpp
// testthirdone
//
// Created by 杜甲 on 14-7-1.
//
//
void hello()
{
log("hello thread");
}
bool PublicScene::init()
{
bool bRet = false;
do {
CC_BREAK_IF(!Scene::init());
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i)
{
threads.push_back(std::thread([ = ]()
{
log("%s",StringUtils::format(" thread %d",i).c_str());
}));
}
for (auto& thread :threads) {
thread.join();
}
log("Main Thread");
bRet = true;
} while (0);
return bRet;
}
3、
//
// PublicScene.cpp
// testthirdone
//
// Created by 杜甲 on 14-7-1.
//
//
void hello()
{
log("hello thread");
}
bool PublicScene::init()
{
bool bRet = false;
do {
CC_BREAK_IF(!Scene::init());
std::mutex m;
std::thread t1([&m](){
m.lock();
for (int i = 0; i < 10; i++) {
log("%s",StringUtils::format(" thread1 %d",i).c_str());
}
m.unlock();
});
std::thread t2([&m](){
m.lock();
for (int i = 0; i < 10; i++) {
log("%s",StringUtils::format(" thread2 %d",i).c_str());
}
m.unlock();
});
t1.join();
t2.join();
log("Main Thread");
bRet = true;
} while (0);
return bRet;
}