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 Marco Costalba
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/>.
21 #if !defined(LOCK_H_INCLUDED)
22 #define LOCK_H_INCLUDED
25 // x86 assembly language locks or OS spin locks may perform faster than
26 // mutex locks on some platforms. On my machine, mutexes seem to be the
30 //#define OS_SPIN_LOCK
36 typedef volatile int Lock;
38 static inline void LockX86(Lock *lock) {
40 asm __volatile__("1: movl $1, %0" "\n\t"
41 " xchgl (%1), %0" "\n\t" " testl %0, %0" "\n\t"
42 " jz 3f" "\n\t" "2: pause" "\n\t"
43 " movl (%1), %0" "\n\t" " testl %0, %0" "\n\t"
44 " jnz 2b" "\n\t" " jmp 1b" "\n\t" "3:"
50 static inline void UnlockX86(Lock *lock) {
52 asm __volatile__("movl $0, (%1)":"=&q"(dummy)
56 # define lock_init(x, y) (*(x) = 0)
57 # define lock_grab(x) LockX86(x)
58 # define lock_release(x) UnlockX86(x)
59 # define lock_destroy(x)
62 #elif defined(OS_SPIN_LOCK)
65 # include <libkern/OSAtomic.h>
67 typedef OSSpinLock Lock;
69 # define lock_init(x, y) (*(x) = 0)
70 # define lock_grab(x) OSSpinLockLock(x)
71 # define lock_release(x) OSSpinLockUnlock(x)
72 # define lock_destroy(x)
75 #elif !defined(_MSC_VER)
79 typedef pthread_mutex_t Lock;
81 # define lock_init(x, y) pthread_mutex_init(x, y)
82 # define lock_grab(x) pthread_mutex_lock(x)
83 # define lock_release(x) pthread_mutex_unlock(x)
84 # define lock_destroy(x) pthread_mutex_destroy(x)
92 typedef CRITICAL_SECTION Lock;
93 # define lock_init(x, y) InitializeCriticalSection(x)
94 # define lock_grab(x) EnterCriticalSection(x)
95 # define lock_release(x) LeaveCriticalSection(x)
96 # define lock_destroy(x) DeleteCriticalSection(x)
102 #endif // !defined(LOCK_H_INCLUDED)