- 本帖最后由 lonely_wm 于 2012-6-14 08:33 编辑 *
在制作的过程中,我将资源数据加载到一个单例工厂中,用CCMultipleArray封装了一些frame和animation,在主线程中加载这些资源都没有问题,问题出在在standtouch相关的touch操作中 和 this->schedule(schedule_selector(testSingle::updates));类似的update函数中,很显然cocos2d-x采用了多线程,在这样的函数中如果声明一个frame或者animation加载(引用)单例模式中的相应的frame或animation就会出错。而且就算将这些资源设置为全局静态变量或者是在前面加上volatile也没有用(经过测试的)。请问哪位大神知道如何从多个线程共享数据的角度解决这个问题,或者从其他方面入手也可以,小弟不甚感激。
附上测试代码,大家也可以帮忙测试一下:
一、在helloWorld.h加上
class testSingle:public CCSprite
{
public:
void load();
void updates(ccTime mTime);
bool isAdded;
};
class Factory
{
public:
CCArray* arrays;
void init();
static Factory * sharedFactory();
};
二、在helloWorld.cpp中加上:
static Factory factory;
static bool isFirst=true;
void testSingle::load()
{
CCSprite::init();
isAdded=false;
this->schedule(schedule_selector(testSingle::updates));
}
void testSingle::updates(ccTime mTime)
{
//确保只运行一次而不是没一帧都调用;
if (!isAdded)
{
Factory fac=Factory::sharedFactory();
CCArray arrayTmp=fac->arrays;
CCSprite spt=(CCSprite)arrayTmp->objectAtIndex(0);
HelloWorld helloworld=(HelloWorld)getParent();
helloworld->addChild(spt);
spt->setPosition(ccp(100,100));
isAdded=true;
}
}
static Factory factory;
static bool isFirst=true;
Factory* Factory::sharedFactory()
{
if (isFirst)
{
isFirst=false;
factory.init();
}
return &factory;
}
void Factory::init()
{
arrays=CCArray::arrayWithCapacity(10);
CCSprite *sprt=CCSprite::spriteWithFile(“HelloWorld.png”);
arrays->addObject(sprt);
}
另外在bool HelloWorld::init()函数的bRet = true;前面加上:
//注意先加载一次fac,让起在主线程中初始化(这个仅在第一次调用的时候初始化),以免后面在update函数中初始化;
//如果将这一句去掉,单例factory将会在子线程中初始化,程序将正常运行,但是此时无法再主线程调用sharedfactory;
Factory* fac=Factory::sharedFactory();
testSingle* te=new testSingle;
te->load();
addChild(te);
大家有兴趣可以测试一下,注意我写的注释。