8bc0491deab907f80c23a157088c97f399536ce6
[libcds.git] / tests / unit / lock / win32_lock.h
1 //$$CDS-header$$
2
3 #ifndef CDSUNIT_LOCK_WIN32_LOCK_H
4 #define CDSUNIT_LOCK_WIN32_LOCK_H
5
6 #if defined(_WIN32) || defined(_WIN64)
7 #define NOMINMAX
8 #include <windows.h>
9
10 #define UNIT_LOCK_WIN_CS
11
12 namespace lock {
13     namespace win {
14         // Win32 critical section
15         class CS {
16             CRITICAL_SECTION    m_cs;
17
18         public:
19             CS()    { ::InitializeCriticalSection( &m_cs ) ; }
20             ~CS()   { ::DeleteCriticalSection( &m_cs ) ; }
21
22             void lock()     { ::EnterCriticalSection( &m_cs ) ; }
23             void unlock()   { ::LeaveCriticalSection( &m_cs)  ; }
24             bool try_lock()  { return ::TryEnterCriticalSection( &m_cs ) != 0 ; }
25         };
26
27         class Mutex {
28             HANDLE  m_hMutex;
29         public:
30
31             Mutex()     { m_hMutex = ::CreateMutex( nullptr, false, nullptr ); }
32             ~Mutex()    { ::CloseHandle( m_hMutex ) ; }
33
34             void lock()     { ::WaitForSingleObject( m_hMutex, INFINITE ); }
35             void unlock()   { ::ReleaseMutex( m_hMutex ); }
36             bool try_lock()  { return ::WaitForSingleObject( m_hMutex, 0) == WAIT_OBJECT_0; }
37         };
38
39     } // namespace win
40 }   // namespace lock
41
42 #endif  // defined(_WIN32) || defined(_WIN64)
43 #endif  // #ifndef CDSUNIT_LOCK_WIN32_LOCK_H