How to run custom network code in another thread in cocos2d-x scene? I'm making turn-based multiplayer game on cocos2d-x and SDL_Net.
Use std::thread
to create and detach second thread:
#include <chrono>
#include <thread>
#include <iostream>
int main(int argc, char *argv[])
{
std::thread thread_name([]()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Hello from other thread" << std::endl;
}
});
thread_name.detach();
std::this_thread::sleep_for(std::chrono::seconds(11));
return 0;
}
Use cocos2d::Scheduler
to schedule actions from that thread:
cocos2d::Director::getInstance()->getScheduler()->schedule([](float)
{
std::cout << "We can operate cocos-related things here" << std::endl;
}, this, 0.0f, 1, 0, false, "name");