RoundPi
RoundPi

Reputation: 5947

cocos2d notification/event/message from a different thread

I have a worker thread doing calculation on the background and I want to send a event/message to call a update function to update the graphics on screen once the worker thread finish calculation.

How do I do that in cocos2d ?

Some demo code:

-(void) updateGraphic
{
//this one update all the graphics/sprite
}

//note workerThreadFunc is being used to start a new thread
-(void) workerThreadFunc
{
//...
//...
//finish calculation here
//since it's in a different thread, I cannot call updateGraphic directly here
//So I need a event to notify update Graphic here somehow

}

Upvotes: 0

Views: 450

Answers (2)

Ring.Yee
Ring.Yee

Reputation: 56

I've achieve it via pthreads, it needs to do some changes in CCDirector.cpp & CCDirector.h the details is in this thread.

to use it, we can register handleMessageInUI in UI thread, then worker thread sends a message to UI thread, which will call handleMessageInUI to do UI drawing. some sample code is below:

  1. In UI thread, we can register a handler to process message in UI thread.

    bool HelloWorldScene::handleMessageInUIThread(const EXTCCMessage &msg) {
    // implementations
    // return true if this handler has processed this msg,
    // otherwise, false is returned
    switch (msg.msgId) {
    case 2:
    break;
    default:
    return false;
    }

    return true;
    }

    // register this Handler to UI Threader
    CCDirector::mainLoopHandler()->registerHandler(this, (EXTCCHandleMessage)&HelloWorldScene::handleMessageInUIThread);

  2. send a message to UI thread in a worker thread

    EXTCCMessage msg;
    msg.msgId = 2;
    msg.msgData1 = NULL;
    // "msg" will be processed by "handleMessageInUIThread" in UI thread
    CCDirector::mainLoopHandler()->postMessage(msg);

Upvotes: 0

CodeSmile
CodeSmile

Reputation: 64477

Cocos2D calls the -(void) draw {} method on all nodes automatically on the main thread. You do not need to call that method from another thread, and you can not perform custom OpenGL drawing outside the draw method.

In order to call a method that should be performed on the main thread, use the performSelectorOnMainThread method.

Upvotes: 2

Related Questions