Aymen
Aymen

Reputation: 422

How to support Multi threading in cocos2d-x

i m using cocos2d-x V3.4 and i still cannot find a good example on how to use multi threading. i m using pthread as worker thread to do some background processing. from within the pthread,i trigger some custom events (Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);) to update the UI.things are working fine as long as the triggered events do not add any graphic to the UI (addChild). moving sprites around doesnt look to have any issue. but once the pthread fires an event (EventCustom) that needs to add a ui node (DrawNode in my case), i get a black screen. from what i could find on the web, the pthread is not supposed to fire those events. he just need to fill up a queue of events and schedule pulling those events from the UIThread to render. What i did was having an std::vector as member of a singleton class GameManager. my pthread pushes to that list. and i scheduled a pulling from that list. but my app keep crashing. So i m pretty sure that what i m doing is not the right way.

Upvotes: 2

Views: 4409

Answers (1)

Rajeev
Rajeev

Reputation: 585

UI related stuff must be performed on cocos thread otherwise it may lead to undefined behaviour as per my experience. You can try following steps:

  1. Create a function that will perform required UI related stuff on a particular event
  2. Call the method from your pthread to be performed on cocos thread as follows:

    auto scheduler = Director::getInstance()->getScheduler();

    scheduler-> performFunctionInCocosThread(CC_CALLBACK_0(YourClass::updateUI, this));

Here updateUI function which is defined in YourClass will be responsible to perform UI related operations.

Upvotes: 6

Related Questions