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

浪尽此生 提交于 2019-12-11 02:55:44

问题


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.


回答1:


Use this to execute your code in main thread:

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



回答2:


The simplest (and propably not the most elegant) way to achieve this is to have a kind of buffer (i.e. an std::list) and a method that would periodically check if there is new data in the buffer. In cocos such a function is an void update(float dt) on every (CC)Scene which is run between each frame, or you could as well schedule your own with desired time interval.

Of course reading and writing to the buffer need to be done in critical sections.



来源:https://stackoverflow.com/questions/21373741/cocos2d-x-loading-sprite-from-another-thread-not-possible-any-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!