forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrape_engine_safe_ptr.hpp
75 lines (60 loc) · 1.52 KB
/
drape_engine_safe_ptr.hpp
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
#pragma once
#include "base/macros.hpp"
#include "drape/drape_global.hpp"
#include "drape/pointers.hpp"
#include <mutex>
namespace df
{
class DrapeEngine;
class DrapeEngineSafePtr
{
public:
void Set(ref_ptr<DrapeEngine> engine)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_engine = engine;
}
explicit operator bool()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_engine != nullptr;
}
template <typename Function, typename ... Args>
void SafeCall(Function && f, Args && ... functionArgs)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_engine != nullptr)
(m_engine.get()->*f)(std::forward<Args>(functionArgs)...);
}
template <typename Function, typename ... Args>
dp::DrapeID SafeCallWithResult(Function && f, Args && ... functionArgs)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_engine != nullptr)
return (m_engine.get()->*f)(std::forward<Args>(functionArgs)...);
return dp::DrapeID();
}
private:
ref_ptr<DrapeEngine> m_engine;
std::mutex m_mutex;
friend class DrapeEngineLockGuard;
};
class DrapeEngineLockGuard
{
public:
explicit DrapeEngineLockGuard(DrapeEngineSafePtr & enginePtr)
: m_ptr(enginePtr)
{
m_ptr.m_mutex.lock();
}
~DrapeEngineLockGuard()
{
m_ptr.m_mutex.unlock();
}
explicit operator bool() { return m_ptr.m_engine != nullptr; }
ref_ptr<DrapeEngine> Get() { return m_ptr.m_engine; }
private:
DrapeEngineSafePtr & m_ptr;
DISALLOW_COPY_AND_MOVE(DrapeEngineLockGuard);
};
} // namespace df