void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback)
{
Texture2D *texture = nullptr;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
auto it = _textures.find(fullpath);
if( it != _textures.end() )
texture = it->second;
if (texture != nullptr)
{
callback(texture);
return;
}
// lazy init
if (_asyncStructQueue == nullptr)
{
_asyncStructQueue = new queue<AsyncStruct*>();
_imageInfoQueue = new deque<ImageInfo*>();
// create a new thread to load images
_loadingThread = new std::thread(&TextureCache::loadImage, this);
_needQuit = false;
}
if (0 == _asyncRefCount)
{
Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false);
}
++_asyncRefCount;
// generate async struct
AsyncStruct *data = new (std::nothrow) AsyncStruct(fullpath, callback);
// add async struct into queue
_asyncStructQueueMutex.lock();
_asyncStructQueue->push(data);
_asyncStructQueueMutex.unlock();
_sleepCondition.notify_one();
}