summaryrefslogtreecommitdiff
path: root/cpp/include/IceUtil/Lock.h
blob: ad713e349a009ee55e2602aa0ba158eb1f4157f9 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//

#ifndef ICE_UTIL_LOCK_H
#define ICE_UTIL_LOCK_H

#include <IceUtil/Config.h>
#include <IceUtil/ThreadException.h>

namespace IceUtil
{

//
// Forward declarations.
//
class Cond;

// LockT and TryLockT are the preferred construct to lock/tryLock/unlock
// simple and recursive mutexes. You typically allocate them on the
// stack to hold a lock on a mutex.
// LockT and TryLockT are not recursive: you cannot acquire several times
// in a row a lock with the same Lock or TryLock object.
//
// We must name this LockT instead of Lock, because otherwise some
// compilers (such as Sun C++ 5.4) have problems with constructs
// such as:
//
// class Foo
// {
//     // ...
//     typedef Lock<Mutex> Lock;
// }
//
template <typename T>
class LockT
{
public:

    LockT(const T& mutex) :
        _mutex(mutex)
    {
        _mutex.lock();
        _acquired = true;
    }

    ~LockT()
    {
        if (_acquired)
        {
            _mutex.unlock();
        }
    }

    void acquire() const
    {
        if (_acquired)
        {
            throw ThreadLockedException(__FILE__, __LINE__);
        }
        _mutex.lock();
        _acquired = true;
    }

    bool tryAcquire() const
    {
        if (_acquired)
        {
            throw ThreadLockedException(__FILE__, __LINE__);
        }
        _acquired = _mutex.tryLock();
        return _acquired;
    }

    void release() const
    {
        if (!_acquired)
        {
            throw ThreadLockedException(__FILE__, __LINE__);
        }
        _mutex.unlock();
        _acquired = false;
    }

    bool acquired() const
    {
        return _acquired;
    }

protected:

    // TryLockT's contructor
    LockT(const T& mutex, bool) :
        _mutex(mutex)
    {
        _acquired = _mutex.tryLock();
    }

private:

    // Not implemented; prevents accidental use.
    //
    LockT(const LockT&);
    LockT& operator=(const LockT&);

    const T& _mutex;
    mutable bool _acquired;

    friend class Cond;
};

//
// Must be named TryLockT, not TryLock. See the comment for LockT for
// an explanation.
//
template <typename T>
class TryLockT : public LockT<T>
{
public:

    TryLockT(const T& mutex) :
        LockT<T>(mutex, true)
    {}
};

} // End namespace IceUtil

#endif