-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResourceManager.h
108 lines (72 loc) · 2.02 KB
/
ResourceManager.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#pragma once
#include <future>
#include <mutex>
#include <memory>
#include <utility>
#include <unordered_map>
template<typename Type, typename KeyType, typename ...Args>
class ResourceManager {
Type(*loadFunc)(Args...);
void(*freeFunc)(Type* instance);
std::mutex dataMutex;
std::unordered_map<KeyType, std::pair<std::shared_ptr<Type>, int>> data;
public:
ResourceManager(Type(*ploadFunc)(Args...), void(*pfreeFunc)(Type* instance) = [](Type * instance) {}) :
loadFunc(ploadFunc), freeFunc(pfreeFunc) {}
~ResourceManager() {
for (auto it : data)
freeFunc(&(*it.second.first));
}
void loadDataAsync(const KeyType& key, Args... args) {
auto future = std::async(std::launch::async, [&]() {
auto pair = std::make_pair(std::make_shared<Type>(loadFunc(std::forward<Args>(args)...)), 0);
dataMutex.lock();
data.emplace(key, pair);
dataMutex.unlock();
});
future.get();
}
std::shared_ptr<Type> getData(const KeyType& key, Args... args) {
dataMutex.lock();
auto it = data.find(key);
if (it == data.end()) {
std::shared_ptr<Type> instance = std::make_shared<Type>(loadFunc(std::forward<Args>(args)...));
data.emplace(key, std::make_pair(instance, 1));
dataMutex.unlock();
return instance;
}
dataMutex.unlock();
it->second.second++;
return it->second.first;
}
std::shared_ptr<Type> getData(const KeyType& key) {
dataMutex.lock();
auto it = data.find(key);
if (it == data.end()) {
dataMutex.unlock();
return nullptr;
}
it->second.second++;
dataMutex.unlock();
return it->second.first;
}
void freeData(const KeyType& key) {
dataMutex.lock();
if (data.size() <= 0) {
dataMutex.unlock();
return;
}
auto it = data.find(key);
if (it == data.end()) {
dataMutex.unlock();
return;
}
if (--it->second.second > 0) {
dataMutex.unlock();
return;
}
freeFunc(&(*it->second.first));
data.erase(it);
dataMutex.unlock();
}
};