Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/mingw-std-threads/mingw.mutex.h
9896 views
1
/**
2
* @file mingw.mutex.h
3
* @brief std::mutex et al implementation for MinGW
4
** (c) 2013-2016 by Mega Limited, Auckland, New Zealand
5
* @author Alexander Vassilev
6
*
7
* @copyright Simplified (2-clause) BSD License.
8
* You should have received a copy of the license along with this
9
* program.
10
*
11
* This code is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
* @note
15
* This file may become part of the mingw-w64 runtime package. If/when this happens,
16
* the appropriate license will be added, i.e. this code will become dual-licensed,
17
* and the current BSD 2-clause license will stay.
18
*/
19
20
#ifndef WIN32STDMUTEX_H
21
#define WIN32STDMUTEX_H
22
23
#if !defined(__cplusplus) || (__cplusplus < 201103L)
24
#error A C++11 compiler is required!
25
#endif
26
// Recursion checks on non-recursive locks have some performance penalty, and
27
// the C++ standard does not mandate them. The user might want to explicitly
28
// enable or disable such checks. If the user has no preference, enable such
29
// checks in debug builds, but not in release builds.
30
#ifdef STDMUTEX_RECURSION_CHECKS
31
#elif defined(NDEBUG)
32
#define STDMUTEX_RECURSION_CHECKS 0
33
#else
34
#define STDMUTEX_RECURSION_CHECKS 1
35
#endif
36
37
#include <chrono>
38
#include <system_error>
39
#include <atomic>
40
#include <mutex> //need for call_once()
41
42
#if STDMUTEX_RECURSION_CHECKS || !defined(NDEBUG)
43
#include <cstdio>
44
#endif
45
46
#include <sdkddkver.h> // Detect Windows version.
47
48
#if (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR))
49
#pragma message "The Windows API that MinGW-w32 provides is not fully compatible\
50
with Microsoft's API. We'll try to work around this, but we can make no\
51
guarantees. This problem does not exist in MinGW-w64."
52
#include <windows.h> // No further granularity can be expected.
53
#else
54
#if STDMUTEX_RECURSION_CHECKS
55
#include <processthreadsapi.h> // For GetCurrentThreadId
56
#endif
57
#include <synchapi.h> // For InitializeCriticalSection, etc.
58
#include <errhandlingapi.h> // For GetLastError
59
#include <handleapi.h>
60
#endif
61
62
// Need for the implementation of invoke
63
#include "mingw.invoke.h"
64
65
#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0501)
66
#error To use the MinGW-std-threads library, you will need to define the macro _WIN32_WINNT to be 0x0501 (Windows XP) or higher.
67
#endif
68
69
namespace mingw_stdthread
70
{
71
// The _NonRecursive class has mechanisms that do not play nice with direct
72
// manipulation of the native handle. This forward declaration is part of
73
// a friend class declaration.
74
#if STDMUTEX_RECURSION_CHECKS
75
namespace vista
76
{
77
class condition_variable;
78
}
79
#endif
80
// To make this namespace equivalent to the thread-related subset of std,
81
// pull in the classes and class templates supplied by std but not by this
82
// implementation.
83
using std::lock_guard;
84
using std::unique_lock;
85
using std::adopt_lock_t;
86
using std::defer_lock_t;
87
using std::try_to_lock_t;
88
using std::adopt_lock;
89
using std::defer_lock;
90
using std::try_to_lock;
91
92
class recursive_mutex
93
{
94
CRITICAL_SECTION mHandle;
95
public:
96
typedef LPCRITICAL_SECTION native_handle_type;
97
native_handle_type native_handle() {return &mHandle;}
98
recursive_mutex() noexcept : mHandle()
99
{
100
InitializeCriticalSection(&mHandle);
101
}
102
recursive_mutex (const recursive_mutex&) = delete;
103
recursive_mutex& operator=(const recursive_mutex&) = delete;
104
~recursive_mutex() noexcept
105
{
106
DeleteCriticalSection(&mHandle);
107
}
108
void lock()
109
{
110
EnterCriticalSection(&mHandle);
111
}
112
void unlock()
113
{
114
LeaveCriticalSection(&mHandle);
115
}
116
bool try_lock()
117
{
118
return (TryEnterCriticalSection(&mHandle)!=0);
119
}
120
};
121
122
#if STDMUTEX_RECURSION_CHECKS
123
struct _OwnerThread
124
{
125
// If this is to be read before locking, then the owner-thread variable must
126
// be atomic to prevent a torn read from spuriously causing errors.
127
std::atomic<DWORD> mOwnerThread;
128
constexpr _OwnerThread () noexcept : mOwnerThread(0) {}
129
static void on_deadlock (void)
130
{
131
using namespace std;
132
fprintf(stderr, "FATAL: Recursive locking of non-recursive mutex\
133
detected. Throwing system exception\n");
134
fflush(stderr);
135
__builtin_trap();
136
}
137
DWORD checkOwnerBeforeLock() const
138
{
139
DWORD self = GetCurrentThreadId();
140
if (mOwnerThread.load(std::memory_order_relaxed) == self)
141
on_deadlock();
142
return self;
143
}
144
void setOwnerAfterLock(DWORD id)
145
{
146
mOwnerThread.store(id, std::memory_order_relaxed);
147
}
148
void checkSetOwnerBeforeUnlock()
149
{
150
DWORD self = GetCurrentThreadId();
151
if (mOwnerThread.load(std::memory_order_relaxed) != self)
152
on_deadlock();
153
mOwnerThread.store(0, std::memory_order_relaxed);
154
}
155
};
156
#endif
157
158
// Though the Slim Reader-Writer (SRW) locks used here are not complete until
159
// Windows 7, implementing partial functionality in Vista will simplify the
160
// interaction with condition variables.
161
162
//Define SRWLOCK_INIT.
163
164
#if !defined(SRWLOCK_INIT)
165
#pragma message "SRWLOCK_INIT macro is not defined. Defining automatically."
166
#define SRWLOCK_INIT {0}
167
#endif
168
169
#if defined(_WIN32) && (WINVER >= _WIN32_WINNT_VISTA)
170
namespace windows7
171
{
172
class mutex
173
{
174
SRWLOCK mHandle;
175
// Track locking thread for error checking.
176
#if STDMUTEX_RECURSION_CHECKS
177
friend class vista::condition_variable;
178
_OwnerThread mOwnerThread {};
179
#endif
180
public:
181
typedef PSRWLOCK native_handle_type;
182
#pragma GCC diagnostic push
183
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
184
constexpr mutex () noexcept : mHandle(SRWLOCK_INIT) { }
185
#pragma GCC diagnostic pop
186
mutex (const mutex&) = delete;
187
mutex & operator= (const mutex&) = delete;
188
void lock (void)
189
{
190
// Note: Undefined behavior if called recursively.
191
#if STDMUTEX_RECURSION_CHECKS
192
DWORD self = mOwnerThread.checkOwnerBeforeLock();
193
#endif
194
AcquireSRWLockExclusive(&mHandle);
195
#if STDMUTEX_RECURSION_CHECKS
196
mOwnerThread.setOwnerAfterLock(self);
197
#endif
198
}
199
void unlock (void)
200
{
201
#if STDMUTEX_RECURSION_CHECKS
202
mOwnerThread.checkSetOwnerBeforeUnlock();
203
#endif
204
ReleaseSRWLockExclusive(&mHandle);
205
}
206
// TryAcquireSRW functions are a Windows 7 feature.
207
#if (WINVER >= _WIN32_WINNT_WIN7)
208
bool try_lock (void)
209
{
210
#if STDMUTEX_RECURSION_CHECKS
211
DWORD self = mOwnerThread.checkOwnerBeforeLock();
212
#endif
213
BOOL ret = TryAcquireSRWLockExclusive(&mHandle);
214
#if STDMUTEX_RECURSION_CHECKS
215
if (ret)
216
mOwnerThread.setOwnerAfterLock(self);
217
#endif
218
return ret;
219
}
220
#endif
221
native_handle_type native_handle (void)
222
{
223
return &mHandle;
224
}
225
};
226
} // Namespace windows7
227
#endif // Compiling for Vista
228
namespace xp
229
{
230
class mutex
231
{
232
CRITICAL_SECTION mHandle;
233
std::atomic_uchar mState;
234
// Track locking thread for error checking.
235
#if STDMUTEX_RECURSION_CHECKS
236
friend class vista::condition_variable;
237
_OwnerThread mOwnerThread {};
238
#endif
239
public:
240
typedef PCRITICAL_SECTION native_handle_type;
241
constexpr mutex () noexcept : mHandle(), mState(2) { }
242
mutex (const mutex&) = delete;
243
mutex & operator= (const mutex&) = delete;
244
~mutex() noexcept
245
{
246
// Undefined behavior if the mutex is held (locked) by any thread.
247
// Undefined behavior if a thread terminates while holding ownership of the
248
// mutex.
249
DeleteCriticalSection(&mHandle);
250
}
251
void lock (void)
252
{
253
unsigned char state = mState.load(std::memory_order_acquire);
254
while (state) {
255
if ((state == 2) && mState.compare_exchange_weak(state, 1, std::memory_order_acquire))
256
{
257
InitializeCriticalSection(&mHandle);
258
mState.store(0, std::memory_order_release);
259
break;
260
}
261
if (state == 1)
262
{
263
Sleep(0);
264
state = mState.load(std::memory_order_acquire);
265
}
266
}
267
#if STDMUTEX_RECURSION_CHECKS
268
DWORD self = mOwnerThread.checkOwnerBeforeLock();
269
#endif
270
EnterCriticalSection(&mHandle);
271
#if STDMUTEX_RECURSION_CHECKS
272
mOwnerThread.setOwnerAfterLock(self);
273
#endif
274
}
275
void unlock (void)
276
{
277
#if STDMUTEX_RECURSION_CHECKS
278
mOwnerThread.checkSetOwnerBeforeUnlock();
279
#endif
280
LeaveCriticalSection(&mHandle);
281
}
282
bool try_lock (void)
283
{
284
unsigned char state = mState.load(std::memory_order_acquire);
285
if ((state == 2) && mState.compare_exchange_strong(state, 1, std::memory_order_acquire))
286
{
287
InitializeCriticalSection(&mHandle);
288
mState.store(0, std::memory_order_release);
289
}
290
if (state == 1)
291
return false;
292
#if STDMUTEX_RECURSION_CHECKS
293
DWORD self = mOwnerThread.checkOwnerBeforeLock();
294
#endif
295
BOOL ret = TryEnterCriticalSection(&mHandle);
296
#if STDMUTEX_RECURSION_CHECKS
297
if (ret)
298
mOwnerThread.setOwnerAfterLock(self);
299
#endif
300
return ret;
301
}
302
native_handle_type native_handle (void)
303
{
304
return &mHandle;
305
}
306
};
307
} // Namespace "xp"
308
#if (WINVER >= _WIN32_WINNT_WIN7)
309
using windows7::mutex;
310
#else
311
using xp::mutex;
312
#endif
313
314
class recursive_timed_mutex
315
{
316
static constexpr DWORD kWaitAbandoned = 0x00000080l;
317
static constexpr DWORD kWaitObject0 = 0x00000000l;
318
static constexpr DWORD kInfinite = 0xffffffffl;
319
inline bool try_lock_internal (DWORD ms) noexcept
320
{
321
DWORD ret = WaitForSingleObject(mHandle, ms);
322
#ifndef NDEBUG
323
if (ret == kWaitAbandoned)
324
{
325
using namespace std;
326
fprintf(stderr, "FATAL: Thread terminated while holding a mutex.");
327
terminate();
328
}
329
#endif
330
return (ret == kWaitObject0) || (ret == kWaitAbandoned);
331
}
332
protected:
333
HANDLE mHandle;
334
// Track locking thread for error checking of non-recursive timed_mutex. For
335
// standard compliance, this must be defined in same class and at the same
336
// access-control level as every other variable in the timed_mutex.
337
#if STDMUTEX_RECURSION_CHECKS
338
friend class vista::condition_variable;
339
_OwnerThread mOwnerThread {};
340
#endif
341
public:
342
typedef HANDLE native_handle_type;
343
native_handle_type native_handle() const {return mHandle;}
344
recursive_timed_mutex(const recursive_timed_mutex&) = delete;
345
recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
346
recursive_timed_mutex(): mHandle(CreateMutex(NULL, FALSE, NULL)) {}
347
~recursive_timed_mutex()
348
{
349
CloseHandle(mHandle);
350
}
351
void lock()
352
{
353
DWORD ret = WaitForSingleObject(mHandle, kInfinite);
354
// If (ret == WAIT_ABANDONED), then the thread that held ownership was
355
// terminated. Behavior is undefined, but Windows will pass ownership to this
356
// thread.
357
#ifndef NDEBUG
358
if (ret == kWaitAbandoned)
359
{
360
using namespace std;
361
fprintf(stderr, "FATAL: Thread terminated while holding a mutex.");
362
terminate();
363
}
364
#endif
365
if ((ret != kWaitObject0) && (ret != kWaitAbandoned))
366
{
367
__builtin_trap();
368
}
369
}
370
void unlock()
371
{
372
if (!ReleaseMutex(mHandle))
373
__builtin_trap();
374
}
375
bool try_lock()
376
{
377
return try_lock_internal(0);
378
}
379
template <class Rep, class Period>
380
bool try_lock_for(const std::chrono::duration<Rep,Period>& dur)
381
{
382
using namespace std::chrono;
383
auto timeout = duration_cast<milliseconds>(dur).count();
384
while (timeout > 0)
385
{
386
constexpr auto kMaxStep = static_cast<decltype(timeout)>(kInfinite-1);
387
auto step = (timeout < kMaxStep) ? timeout : kMaxStep;
388
if (try_lock_internal(static_cast<DWORD>(step)))
389
return true;
390
timeout -= step;
391
}
392
return false;
393
}
394
template <class Clock, class Duration>
395
bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time)
396
{
397
return try_lock_for(timeout_time - Clock::now());
398
}
399
};
400
401
// Override if, and only if, it is necessary for error-checking.
402
#if STDMUTEX_RECURSION_CHECKS
403
class timed_mutex: recursive_timed_mutex
404
{
405
public:
406
timed_mutex() = default;
407
timed_mutex(const timed_mutex&) = delete;
408
timed_mutex& operator=(const timed_mutex&) = delete;
409
void lock()
410
{
411
DWORD self = mOwnerThread.checkOwnerBeforeLock();
412
recursive_timed_mutex::lock();
413
mOwnerThread.setOwnerAfterLock(self);
414
}
415
void unlock()
416
{
417
mOwnerThread.checkSetOwnerBeforeUnlock();
418
recursive_timed_mutex::unlock();
419
}
420
template <class Rep, class Period>
421
bool try_lock_for(const std::chrono::duration<Rep,Period>& dur)
422
{
423
DWORD self = mOwnerThread.checkOwnerBeforeLock();
424
bool ret = recursive_timed_mutex::try_lock_for(dur);
425
if (ret)
426
mOwnerThread.setOwnerAfterLock(self);
427
return ret;
428
}
429
template <class Clock, class Duration>
430
bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time)
431
{
432
return try_lock_for(timeout_time - Clock::now());
433
}
434
bool try_lock ()
435
{
436
return try_lock_for(std::chrono::milliseconds(0));
437
}
438
};
439
#else
440
typedef recursive_timed_mutex timed_mutex;
441
#endif
442
443
class once_flag
444
{
445
// When available, the SRW-based mutexes should be faster than the
446
// CriticalSection-based mutexes. Only try_lock will be unavailable in Vista,
447
// and try_lock is not used by once_flag.
448
#if (_WIN32_WINNT == _WIN32_WINNT_VISTA)
449
windows7::mutex mMutex;
450
#else
451
mutex mMutex;
452
#endif
453
std::atomic_bool mHasRun;
454
once_flag(const once_flag&) = delete;
455
once_flag& operator=(const once_flag&) = delete;
456
template<class Callable, class... Args>
457
friend void call_once(once_flag& once, Callable&& f, Args&&... args);
458
public:
459
constexpr once_flag() noexcept: mMutex(), mHasRun(false) {}
460
};
461
462
template<class Callable, class... Args>
463
void call_once(once_flag& flag, Callable&& func, Args&&... args)
464
{
465
if (flag.mHasRun.load(std::memory_order_acquire))
466
return;
467
lock_guard<decltype(flag.mMutex)> lock(flag.mMutex);
468
if (flag.mHasRun.load(std::memory_order_relaxed))
469
return;
470
detail::invoke(std::forward<Callable>(func),std::forward<Args>(args)...);
471
flag.mHasRun.store(true, std::memory_order_release);
472
}
473
} // Namespace mingw_stdthread
474
475
// Push objects into std, but only if they are not already there.
476
namespace std
477
{
478
// Because of quirks of the compiler, the common "using namespace std;"
479
// directive would flatten the namespaces and introduce ambiguity where there
480
// was none. Direct specification (std::), however, would be unaffected.
481
// Take the safe option, and include only in the presence of MinGW's win32
482
// implementation.
483
#if defined(__MINGW32__ ) && !defined(_GLIBCXX_HAS_GTHREADS) && !defined(__clang__)
484
using mingw_stdthread::recursive_mutex;
485
using mingw_stdthread::mutex;
486
using mingw_stdthread::recursive_timed_mutex;
487
using mingw_stdthread::timed_mutex;
488
using mingw_stdthread::once_flag;
489
using mingw_stdthread::call_once;
490
#elif !defined(MINGW_STDTHREAD_REDUNDANCY_WARNING) // Skip repetition
491
#define MINGW_STDTHREAD_REDUNDANCY_WARNING
492
#pragma message "This version of MinGW seems to include a win32 port of\
493
pthreads, and probably already has C++11 std threading classes implemented,\
494
based on pthreads. These classes, found in namespace std, are not overridden\
495
by the mingw-std-thread library. If you would still like to use this\
496
implementation (as it is more lightweight), use the classes provided in\
497
namespace mingw_stdthread."
498
#endif
499
}
500
#endif // WIN32STDMUTEX_H
501
502