mutex added when accessing the cache

This commit is contained in:
Uwe Rathmann 2020-09-22 12:33:31 +02:00
parent 65a73f949e
commit 31244327f2

View File

@ -7,6 +7,7 @@
#include "QskGraphic.h" #include "QskGraphic.h"
#include "QskSetup.h" #include "QskSetup.h"
#include <qmutex.h>
#include <qcache.h> #include <qcache.h>
#include <qdebug.h> #include <qdebug.h>
#include <qurl.h> #include <qurl.h>
@ -16,6 +17,7 @@ class QskGraphicProvider::PrivateData
public: public:
// caching of graphics // caching of graphics
QCache< QString, const QskGraphic > cache; QCache< QString, const QskGraphic > cache;
QMutex mutex;
}; };
QskGraphicProvider::QskGraphicProvider( QObject* parent ) QskGraphicProvider::QskGraphicProvider( QObject* parent )
@ -33,34 +35,55 @@ void QskGraphicProvider::setCacheSize( int size )
if ( size < 0 ) if ( size < 0 )
size = 0; size = 0;
QMutexLocker locker( &m_data->mutex );
m_data->cache.setMaxCost( size ); m_data->cache.setMaxCost( size );
} }
int QskGraphicProvider::cacheSize() const int QskGraphicProvider::cacheSize() const
{ {
QMutexLocker locker( &m_data->mutex );
return m_data->cache.maxCost(); return m_data->cache.maxCost();
} }
void QskGraphicProvider::clearCache() void QskGraphicProvider::clearCache()
{ {
QMutexLocker locker( &m_data->mutex );
m_data->cache.clear(); m_data->cache.clear();
} }
const QskGraphic* QskGraphicProvider::requestGraphic( const QString& id ) const const QskGraphic* QskGraphicProvider::requestGraphic( const QString& id ) const
{ {
const QskGraphic* graphic = m_data->cache.object( id ); const QskGraphic* graphic = nullptr;
{
QMutexLocker locker( &m_data->mutex );
graphic = m_data->cache.object( id );
}
if ( graphic == nullptr ) if ( graphic == nullptr )
{ {
graphic = loadGraphic( id ); graphic = loadGraphic( id );
if ( graphic == nullptr ) if ( graphic == nullptr )
{ {
qWarning() << "QskGraphicProvider: can't load" << id; qWarning() << "QskGraphicProvider: can't load" << id;
return nullptr; return nullptr;
} }
const int cost = 1; // TODO ... {
m_data->cache.insert( id, graphic, cost ); QMutexLocker locker( &m_data->mutex );
if( auto cached = m_data->cache.object( id ) )
{
delete graphic;
graphic = cached;
}
else
{
const int cost = 1; // TODO ...
m_data->cache.insert( id, graphic, cost );
}
}
} }
return graphic; return graphic;