问题
Facts of my program
- Cocos2d-x main loop runs in its own thread. Let's call it cocos2d-x-thread.
- 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. - 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
- 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