Skip to content

Commit 617009f

Browse files
xiaoyur347minggo
authored andcommitted
fix CCTextureCache addImageAsync race condition (cocos2d#18366)
1 parent 6e535f4 commit 617009f

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

cocos/renderer/CCTextureCache.cpp

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,8 @@ void TextureCache::addImageAsync(const std::string &path, const std::function<vo
214214
if (_loadingThread == nullptr)
215215
{
216216
// create a new thread to load images
217-
_loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
218217
_needQuit = false;
218+
_loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
219219
}
220220

221221
if (0 == _asyncRefCount)
@@ -231,10 +231,8 @@ void TextureCache::addImageAsync(const std::string &path, const std::function<vo
231231

232232
// add async struct into queue
233233
_asyncStructQueue.push_back(data);
234-
_requestMutex.lock();
234+
std::unique_lock<std::mutex> ul(_requestMutex);
235235
_requestQueue.push_back(data);
236-
_requestMutex.unlock();
237-
238236
_sleepCondition.notify_one();
239237
}
240238

@@ -270,12 +268,10 @@ void TextureCache::unbindAllImageAsync()
270268
void TextureCache::loadImage()
271269
{
272270
AsyncStruct *asyncStruct = nullptr;
273-
std::mutex signalMutex;
274-
std::unique_lock<std::mutex> signal(signalMutex);
275271
while (!_needQuit)
276272
{
273+
std::unique_lock<std::mutex> ul(_requestMutex);
277274
// pop an AsyncStruct from request queue
278-
_requestMutex.lock();
279275
if (_requestQueue.empty())
280276
{
281277
asyncStruct = nullptr;
@@ -285,12 +281,15 @@ void TextureCache::loadImage()
285281
asyncStruct = _requestQueue.front();
286282
_requestQueue.pop_front();
287283
}
288-
_requestMutex.unlock();
289284

290285
if (nullptr == asyncStruct) {
291-
_sleepCondition.wait(signal);
286+
if (_needQuit) {
287+
break;
288+
}
289+
_sleepCondition.wait(ul);
292290
continue;
293291
}
292+
ul.unlock();
294293

295294
// load image
296295
asyncStruct->loadSuccess = asyncStruct->image.initWithImageFileThreadSafe(asyncStruct->filename);
@@ -660,8 +659,10 @@ std::string TextureCache::getTextureFilePath(cocos2d::Texture2D* texture) const
660659
void TextureCache::waitForQuit()
661660
{
662661
// notify sub thread to quick
662+
std::unique_lock<std::mutex> ul(_requestMutex);
663663
_needQuit = true;
664664
_sleepCondition.notify_one();
665+
ul.unlock();
665666
if (_loadingThread) _loadingThread->join();
666667
}
667668

0 commit comments

Comments
 (0)