Cocos2d-x 3.0でマルチスレッド処理をする

最近はCocos2d-xの3系を触っているのですが、マルチスレッド処理の部分を試したので忘れないように書いておきます。メインスレッド -> 別スレッド -> メインスレッドの流れで動きます。C++11便利ですね。

std::mutex mtx;

bool HelloWorld::init()
{
    if ( !Layer::init() ) {
        return false;
    }

    // 別スレッドを生成して引数を渡して実行する
    auto t = std::thread([this] (int n) {
        mtx.lock();
        std::cout << "thread is: " << std::this_thread::get_id() << std::endl;
        mtx.unlock();
        
        for (int i = 0; i < 100000; i++) {
            mtx.lock();
            log("%d", n + i);
            mtx.unlock();
        }
        
        // 処理が一通り終わったのでメインスレッドに戻してメソッドを呼ぶ
        auto scheduler = Director::getInstance()->getScheduler();
        scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::dispatchThreadCallbacks, this));
    }, 100);
    
    // スレッドの管理を手放す
    // スレッドの処理を待つ場合はt.join()かstd::asyncを使う
    t.detach();

    // メインスレッドのThread Idを出力
    // 共有リソースを使うのでlock (これがなければ別スレッドに出力を割り込まれる)
    mtx.lock();
    std::cout << "thread is: " << std::this_thread::get_id() << std::endl;
    mtx.unlock();   
}

void HelloWorld::dispatchThreadCallbacks()
{
    // std::lock_guardはunlockをスコープから抜ける時に自動的にやってくれる
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "thread is: " << std::this_thread::get_id() << std::endl;   
}

出力

thread is: 0x3ba71a8
thread is: 0xb0115000
cocos2d: 100
cocos2d: 101
cocos2d: 102
...
thread is: 0x3ba71a8
C++11のthreadで遊んでみる - minus9d's diary
本の虫: GNU/LinuxのC++11でプログラミングの常識がひっくりかえった