-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathreentrancy_guard.h
75 lines (63 loc) · 2.17 KB
/
reentrancy_guard.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
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
//
// Type that's useful to detect reentrancy. This can be useful at either global for function-static scope. Note however,
// that either should be declared 'thread_local'. E.g. Use might look like:
// void FooFixup()
// {
// thread_local psf::reentrancy_guard reentrancyGuard;
// auto guard = reentrancyGuard.enter();
// if (guard) { /*fixup code here*/ }
// return FooImpl();
// }
#pragma once
#include <utility>
namespace psf
{
namespace details
{
struct restore_on_exit
{
restore_on_exit(bool& target, bool restoreValue) :
m_target(&target),
m_restoreValue(restoreValue)
{
}
restore_on_exit(const restore_on_exit&) = delete;
restore_on_exit& operator=(const restore_on_exit&) = delete;
restore_on_exit(restore_on_exit&& other) :
m_target(other.m_target),
m_restoreValue(other.m_restoreValue)
{
other.m_target = nullptr;
}
~restore_on_exit()
{
if (m_target)
{
*m_target = m_restoreValue;
}
}
explicit operator bool()
{
return !m_restoreValue;
}
private:
bool* m_target;
bool m_restoreValue;
};
}
class reentrancy_guard
{
public:
details::restore_on_exit enter()
{
auto restoreValue = std::exchange(m_isReentrant, true);
return details::restore_on_exit{ m_isReentrant, restoreValue };
}
private:
bool m_isReentrant = false;
};
}