forked from tapetums/include
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WinMutex.hpp
76 lines (54 loc) · 1.64 KB
/
WinMutex.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
76
#pragma once
//---------------------------------------------------------------------------//
//
// WinMutex.hpp
// ミューテックスのRAII
// Copyright (C) 2016 tapetums
//
//---------------------------------------------------------------------------//
#include <windows.h>
//---------------------------------------------------------------------------//
namespace tapetums
{
class WinMutex;
}
//---------------------------------------------------------------------------//
class tapetums::WinMutex
{
private:
HANDLE mutex { nullptr };
public:
WinMutex() noexcept = default;
~WinMutex() { release(); ::CloseHandle(mutex); }
WinMutex(const WinMutex&) = delete;
WinMutex& operator =(const WinMutex&) = delete;
WinMutex(WinMutex&&) noexcept = delete;
WinMutex& operator =(WinMutex&&) noexcept = delete;
explicit WinMutex(LPCTSTR name, bool own = true){ lock(name, own); }
public:
operator HANDLE() { return mutex; }
public:
bool lock(LPCTSTR name, bool own)
{
if ( mutex ) { return true; }
mutex = ::CreateMutex(nullptr, own, name));
if ( ::GetLastError() == ERROR_ALREADY_EXISTS )
{
mutex = ::OpenMutex(MUTEX_ALL_ACCESS , own, name));
}
return mutex != nullptr;
}
bool lock()
{
if ( nullptr == mutex ) { return false; }
mutex = ::OpenMutex(MUTEX_ALL_ACCESS , own, name));
return mutex != nullptr;
}
void release()
{
if ( nullptr == mutex ) { return; }
::ReleaseMutex(mutex);
}
};
//---------------------------------------------------------------------------//
// WinMutex.hpp