来自不同线程的cocos2d通知/事件/消息

时间:2011-11-22 23:22:05

标签: multithreading events notifications cocos2d-iphone

我有一个工作线程在后台进行计算,我想发送一个事件/消息来调用更新函数,以便在工作线程完成计算后更新屏幕上的图形。

我如何在cocos2d中执行此操作?

一些演示代码:

-(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

}

2 个答案:

答案 0 :(得分:2)

Cocos2D在主线程上自动调用所有节点上的-(void) draw {}方法。您不需要从另一个线程调用该方法,也不能在draw方法之外执行自定义OpenGL绘图。

要调用应在主线程上执行的方法,请使用performSelectorOnMainThread方法。

答案 1 :(得分:0)

我通过pthreads实现它,它需要在CCDirector.cpp和amp;中做一些改变。 CCDirector.h 详细信息位于this thread.

使用它,我们可以在UI线程中注册handleMessageInUI,然后工作线程向UI线程发送消息,该线程将调用handleMessageInUI来进行UI绘图。下面是一些示例代码:

  1. 在UI线程中,我们可以注册一个处理程序来处理UI线程中的消息。

    bool HelloWorldScene :: handleMessageInUIThread(const EXTCCMessage& msg){
    //实施
    //如果此处理程序已处理此消息,则返回true,
    //否则,返回false 开关(msg.msgId){
    案例2:
    打破;
    默认:
    返回false;
    }

    返回true;
    }

    //将此Handler注册到UI Threader
    CCDirector :: mainLoopHandler() - > registerHandler(this,(EXTCCHandleMessage)& HelloWorldScene :: handleMessageInUIThread);

  2. 向工作线程中的UI线程发送消息

    EXTCCMessage msg;
    msg.msgId = 2;
    msg.msgData1 = NULL;
    //“msg”将由UI线程中的“handleMessageInUIThread”处理 CCDirector :: mainLoopHandler() - >的postMessage(MSG);