2017-01-04 15:12:31 +01:00
|
|
|
#ifndef CONCURRENTMAP_H
|
|
|
|
#define CONCURRENTMAP_H
|
|
|
|
|
2017-01-06 23:28:48 +01:00
|
|
|
#include <QMap>
|
2017-01-11 18:52:09 +01:00
|
|
|
#include <QMutex>
|
2017-01-06 23:28:48 +01:00
|
|
|
#include <functional>
|
2017-01-26 09:26:18 +01:00
|
|
|
#include <unordered_map>
|
2017-01-04 15:12:31 +01:00
|
|
|
|
2017-01-18 21:30:23 +01:00
|
|
|
namespace chatterino {
|
|
|
|
|
2017-01-11 18:52:09 +01:00
|
|
|
template <typename TKey, typename TValue>
|
2017-01-04 15:12:31 +01:00
|
|
|
class ConcurrentMap
|
|
|
|
{
|
|
|
|
public:
|
2017-01-11 18:52:09 +01:00
|
|
|
ConcurrentMap()
|
2017-01-26 09:26:18 +01:00
|
|
|
: map()
|
2017-01-11 18:52:09 +01:00
|
|
|
{
|
2017-01-26 09:26:18 +01:00
|
|
|
this->mutex = new QMutex();
|
2017-01-04 15:12:31 +01:00
|
|
|
}
|
|
|
|
|
2017-01-11 18:52:09 +01:00
|
|
|
bool
|
|
|
|
tryGet(const TKey &name, TValue &value) const
|
|
|
|
{
|
2017-01-26 09:26:18 +01:00
|
|
|
this->mutex->lock();
|
|
|
|
auto a = map.find(name);
|
|
|
|
if (a == map.end()) {
|
|
|
|
this->mutex->unlock();
|
2017-01-04 15:12:31 +01:00
|
|
|
return false;
|
|
|
|
}
|
2017-01-26 09:26:18 +01:00
|
|
|
this->mutex->unlock();
|
2017-01-04 15:12:31 +01:00
|
|
|
value = a.value();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2017-01-11 18:52:09 +01:00
|
|
|
TValue
|
|
|
|
getOrAdd(const TKey &name, std::function<TValue()> addLambda)
|
|
|
|
{
|
2017-01-26 09:26:18 +01:00
|
|
|
this->mutex->lock();
|
|
|
|
auto a = map.find(name);
|
|
|
|
|
|
|
|
if (a == map.end()) {
|
2017-01-04 15:12:31 +01:00
|
|
|
TValue value = addLambda();
|
2017-01-26 09:26:18 +01:00
|
|
|
map.insert(name, value);
|
|
|
|
this->mutex->unlock();
|
2017-01-04 15:12:31 +01:00
|
|
|
return value;
|
|
|
|
}
|
2017-01-26 09:26:18 +01:00
|
|
|
|
|
|
|
this->mutex->unlock();
|
2017-01-04 15:12:31 +01:00
|
|
|
return a.value();
|
|
|
|
}
|
|
|
|
|
2017-01-11 18:52:09 +01:00
|
|
|
void
|
|
|
|
clear()
|
|
|
|
{
|
2017-01-26 09:26:18 +01:00
|
|
|
this->mutex->lock();
|
|
|
|
map.clear();
|
|
|
|
this->mutex->unlock();
|
2017-01-04 15:12:31 +01:00
|
|
|
}
|
|
|
|
|
2017-01-11 18:52:09 +01:00
|
|
|
void
|
|
|
|
insert(const TKey &name, const TValue &value)
|
|
|
|
{
|
2017-01-26 09:26:18 +01:00
|
|
|
this->mutex->lock();
|
|
|
|
map.insert(name, value);
|
|
|
|
this->mutex->unlock();
|
2017-01-04 15:12:31 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2017-01-11 18:52:09 +01:00
|
|
|
QMutex *mutex;
|
2017-01-26 09:26:18 +01:00
|
|
|
QMap<TKey, TValue> map;
|
2017-01-04 15:12:31 +01:00
|
|
|
};
|
2017-01-18 21:30:23 +01:00
|
|
|
}
|
2017-01-04 15:12:31 +01:00
|
|
|
|
2017-01-11 18:52:09 +01:00
|
|
|
#endif // CONCURRENTMAP_H
|