2011-11-22 54 views
0

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

如何在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 

} 
+0

我的感觉是,即使在基本工作之前,您也正朝着线程化实现方向发展。首先实现你的应用程序可能是值得的,然后再考虑是否值得做多线程编程。尤其是因为迄今为止唯一具有多个硬件线程的iOS设备是iPad 2和iPhone 4S。 – LearnCocos2D

回答

2

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

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

0

我已经通过并行线程实现它,它需要做的CCDirector.cpp一些变化& CCDirector.h 细节在this thread.

使用它,我们可以在UI线程注册handleMessageInUI,然后工人线程向UI线程发送消息,该线程将调用handleMessageInUI进行UI绘制。一些示例代码低于:

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

    布尔HelloWorldScene :: handleMessageInUIThread(常量EXTCCMessage & MSG){如果该处理程序已处理此味精,
    //否则,则返回false
    开关
    //实现
    //返回true(MSG。 msgId){
    case 2:
    break;
    默认值:
    返回false;
    }

    return true;
    }

    //注册此处理到UI穿线
    CCDirector :: mainLoopHandler() - > registerHandler(此,(EXTCCHandleMessage)& HelloWorldScene :: handleMessageInUIThread);

  2. 在辅助线程

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