Search code examples
c++multithreadingdesign-patternscocos2d-x

cocos2d-x: loading sprite from another thread not possible, any pattern?


Facts of my program

  1. Cocos2d-x main loop runs in its own thread. Let's call it cocos2d-x-thread.
  2. I have a task_scheduler that runs in its own thread, in which you can submit lightweight tasks. Let's call it task_scheduler-thread.
  3. Every x milliseconds, a callback is emitted from the task_scheduler thread. Let's call it task_scheduler-tick-callback.

What I want to do

I want to load a sprite when task_scheduler-tick-callback is emitted, but I cannot do it from that thread, so I will have to submit some kind of work to be performed by cocos2d-x thread.

Problem

  1. How can I make cocos2d-x-thread, when receiving this work, to be executed? Because cocos2d-x is already running its own loop and I want to avoid injecting custom code to the cocos2d-x generated project at all costs.

Any patterns?

EDIT: Idea -> any callback function called for each loop iteration in cocos2d-x? Does that exist? I could integrate the call to my work piece like that.


Solution

  • Use this to execute your code in main thread:

    Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{
        // your code
    });