2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish 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. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #ifndef THREAD_WIN32_H_INCLUDED
21 #define THREAD_WIN32_H_INCLUDED
23 /// STL thread library used by mingw and gcc when cross compiling for Windows
24 /// relies on libwinpthread. Currently libwinpthread implements mutexes directly
25 /// on top of Windows semaphores. Semaphores, being kernel objects, require kernel
26 /// mode transition in order to lock or unlock, which is very slow compared to
27 /// interlocked operations (about 30% slower on bench test). To workaround this
28 /// issue, we define our wrappers to the low level Win32 calls. We use critical
29 /// sections to support Windows XP and older versions. Unfortunately, cond_wait()
30 /// is racy between unlock() and WaitForSingleObject() but they have the same
31 /// speed performance of SRW locks.
33 #include <condition_variable>
36 #if defined(_WIN32) && !defined(_MSC_VER)
39 # define NOMINMAX // Disable macros min() and max()
42 #define WIN32_LEAN_AND_MEAN
44 #undef WIN32_LEAN_AND_MEAN
47 /// Mutex and ConditionVariable struct are wrappers of the low level locking
48 /// machinery and are modeled after the corresponding C++11 classes.
51 Mutex() { InitializeCriticalSection(&cs); }
52 ~Mutex() { DeleteCriticalSection(&cs); }
53 void lock() { EnterCriticalSection(&cs); }
54 void unlock() { LeaveCriticalSection(&cs); }
60 struct ConditionVariable {
61 ConditionVariable() { hn = CreateEvent(0, FALSE, FALSE, 0); }
62 ~ConditionVariable() { CloseHandle(hn); }
63 void notify_one() { SetEvent(hn); }
65 void wait(std::unique_lock<Mutex>& lk) {
67 WaitForSingleObject(hn, INFINITE);
71 void wait_for(std::unique_lock<Mutex>& lk, const std::chrono::milliseconds& ms) {
73 WaitForSingleObject(hn, ms.count());
77 template<class Predicate>
78 void wait(std::unique_lock<Mutex>& lk, Predicate p) { while (!p()) this->wait(lk); }
84 #else // Default case: use STL classes
86 typedef std::mutex Mutex;
87 typedef std::condition_variable ConditionVariable;
91 #endif // #ifndef THREAD_WIN32_H_INCLUDED