make use of convenience class QMutexLocker in ConcurrentMap
This commit is contained in:
+13
-12
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
#include <QMap>
|
#include <QMap>
|
||||||
#include <QMutex>
|
#include <QMutex>
|
||||||
|
#include <QMutexLocker>
|
||||||
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
@@ -21,54 +22,54 @@ public:
|
|||||||
bool
|
bool
|
||||||
tryGet(const TKey &name, TValue &value) const
|
tryGet(const TKey &name, TValue &value) const
|
||||||
{
|
{
|
||||||
this->mutex.lock();
|
QMutexLocker lock(&this->mutex);
|
||||||
|
|
||||||
auto a = map.find(name);
|
auto a = map.find(name);
|
||||||
if (a == map.end()) {
|
if (a == map.end()) {
|
||||||
this->mutex.unlock();
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
value = a.value();
|
value = a.value();
|
||||||
this->mutex.unlock();
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TValue
|
TValue
|
||||||
getOrAdd(const TKey &name, std::function<TValue()> addLambda)
|
getOrAdd(const TKey &name, std::function<TValue()> addLambda)
|
||||||
{
|
{
|
||||||
this->mutex.lock();
|
QMutexLocker lock(&this->mutex);
|
||||||
auto a = map.find(name);
|
|
||||||
|
|
||||||
|
auto a = map.find(name);
|
||||||
if (a == map.end()) {
|
if (a == map.end()) {
|
||||||
TValue value = addLambda();
|
TValue value = addLambda();
|
||||||
map.insert(name, value);
|
map.insert(name, value);
|
||||||
this->mutex.unlock();
|
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
this->mutex.unlock();
|
|
||||||
return a.value();
|
return a.value();
|
||||||
}
|
}
|
||||||
|
|
||||||
void
|
void
|
||||||
clear()
|
clear()
|
||||||
{
|
{
|
||||||
this->mutex.lock();
|
QMutexLocker lock(&this->mutex);
|
||||||
|
|
||||||
map.clear();
|
map.clear();
|
||||||
this->mutex.unlock();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void
|
void
|
||||||
insert(const TKey &name, const TValue &value)
|
insert(const TKey &name, const TValue &value)
|
||||||
{
|
{
|
||||||
this->mutex.lock();
|
QMutexLocker lock(&this->mutex);
|
||||||
|
|
||||||
map.insert(name, value);
|
map.insert(name, value);
|
||||||
this->mutex.unlock();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
mutable QMutex mutex;
|
mutable QMutex mutex;
|
||||||
QMap<TKey, TValue> map;
|
QMap<TKey, TValue> map;
|
||||||
};
|
};
|
||||||
}
|
|
||||||
|
} // namespace chatterino
|
||||||
|
|
||||||
#endif // CONCURRENTMAP_H
|
#endif // CONCURRENTMAP_H
|
||||||
|
|||||||
Reference in New Issue
Block a user