aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/byzantine-lab/mcl/include/cybozu/critical_section.hpp
blob: 13d7f3a0e567a8da3938d7f4401e21cb085d6480 (plain) (blame)
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
#pragma once
/**
    @file
    @brief critical section

    @author MITSUNARI Shigeo(@herumi)
    @author MITSUNARI Shigeo
*/
#include <cybozu/mutex.hpp>

namespace cybozu {

class ConditionVariableCs;

namespace thread {

#ifdef _WIN32
typedef CRITICAL_SECTION CsHandle;
inline void CsInit(CsHandle& cs) { InitializeCriticalSection(&cs); }
inline void CsLock(CsHandle& cs) { EnterCriticalSection(&cs); }
inline void CsUnlock(CsHandle& cs) { LeaveCriticalSection(&cs); }
inline void CsTerm(CsHandle& cs) { DeleteCriticalSection(&cs); }
#else
typedef pthread_mutex_t CsHandle;
inline void CsInit(CsHandle& cs) { pthread_mutex_init(&cs, NULL); }
inline void CsLock(CsHandle& cs) { pthread_mutex_lock(&cs); }
inline void CsUnlock(CsHandle& cs) { pthread_mutex_unlock(&cs); }
inline void CsTerm(CsHandle& cs) { pthread_mutex_destroy(&cs); }
#endif

} // cybozu::thread

class CriticalSection {
    friend class cybozu::ConditionVariableCs;
public:
    CriticalSection()
    {
        thread::CsInit(hdl_);
    }
    ~CriticalSection()
    {
        thread::CsTerm(hdl_);
    }
    inline void lock()
    {
        thread::CsLock(hdl_);
    }
    inline void unlock()
    {
        thread::CsUnlock(hdl_);
    }
private:
    CriticalSection(const CriticalSection&);
    CriticalSection& operator=(const CriticalSection&);
    thread::CsHandle hdl_;
};

typedef cybozu::thread::AutoLockT<cybozu::CriticalSection> AutoLockCs; //!< auto lock critical section

} // cybozu