cocos2d-x中源代码是
void TextureCache::loadImage()
{
AsyncStruct *asyncStruct = nullptr;
while (true)
{
std::queue<AsyncStruct*> *pQueue = _asyncStructQueue;
_asyncStructQueueMutex.lock();
if (pQueue->empty())
{
_asyncStructQueueMutex.unlock();
if (_needQuit) {
break;
}
else {
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
}
else
{
asyncStruct = pQueue->front();
pQueue->pop();
_asyncStructQueueMutex.unlock();
}
Image *image = nullptr;
bool generateImage = false;
auto it = _textures.find(asyncStruct->filename);
if( it == _textures.end() )
{
_imageInfoMutex.lock();
ImageInfo *imageInfo;
size_t pos = 0;
size_t infoSize = _imageInfoQueue->size();
for (; pos < infoSize; pos++)
{
imageInfo = (*_imageInfoQueue);
if(imageInfo->asyncStruct->filename.compare(asyncStruct->filename))
break;
}
_imageInfoMutex.unlock();
if(infoSize == 0 || pos < infoSize)
generateImage = true;
//这一段语义有点奇怪,我的理解应该是如果从队列中找到和要加载的文件名一样,那么就不需要加载了,因为已经有了
//但代码中compare如果发现不相等就直接break了,也就是说只有队列中没有一样的,那么就重新new一个image ,求解答
}
if (generateImage)
{
const std::string& filename = asyncStruct->filename;
// generate image
image = new Image();
if (image && !image->initWithImageFileThreadSafe(filename))
{
CC_SAFE_RELEASE(image);
CCLOG("can not load %s", filename.c_str());
continue;
}
}
// generate image info
ImageInfo *imageInfo = new ImageInfo();
imageInfo->asyncStruct = asyncStruct;
imageInfo->image = image;
// put the image info into the queue
_imageInfoMutex.lock();
_imageInfoQueue->push_back(imageInfo);
_imageInfoMutex.unlock();
}
if(_asyncStructQueue != nullptr)
{
delete _asyncStructQueue;
_asyncStructQueue = nullptr;
delete _imageInfoQueue;
_imageInfoQueue = nullptr;
}
}