summaryrefslogtreecommitdiffstats
path: root/src/lib/util/threads/sync.cc
blob: 460e6297b2c6abbd269f945a172e81685a8ebf7d (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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright (C) 2012, 2015  Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <util/threads/sync.h>

#include <exceptions/exceptions.h>

#include <cstring>
#include <memory>
#include <cerrno>
#include <cassert>

#include <pthread.h>

using std::auto_ptr;

namespace isc {
namespace util {
namespace thread {

class Mutex::Impl {
public:
    Impl()
#ifdef ENABLE_DEBUG
        : locked_count(0)
#endif // ENABLE_DEBUG
    {}

    pthread_mutex_t mutex;
#ifdef ENABLE_DEBUG
    size_t locked_count;
#endif // ENABLE_DEBUG
};

namespace {

struct Deinitializer {
    Deinitializer(pthread_mutexattr_t& attributes):
        attributes_(attributes)
    {}
    ~Deinitializer() {
        const int result = pthread_mutexattr_destroy(&attributes_);
        // This should never happen. According to the man page,
        // if there's error, it's our fault.
        assert(result == 0);
    }
    pthread_mutexattr_t& attributes_;
};

}

Mutex::Mutex() :
    impl_(NULL)
{
    pthread_mutexattr_t attributes;
    int result = pthread_mutexattr_init(&attributes);
    switch (result) {
        case 0: // All 0K
            break;
        case ENOMEM:
            throw std::bad_alloc();
        default:
            isc_throw(isc::InvalidOperation, std::strerror(result));
    }
    Deinitializer deinitializer(attributes);

    // If debug mode is enabled in compilation, use the slower
    // error-checking mutexes that detect deadlocks. Otherwise, use fast
    // mutexes which don't. See the pthread_mutexattr_settype() POSIX
    // documentation which describes these type attributes.
#ifdef ENABLE_DEBUG
    result = pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_ERRORCHECK);
#else
    result = pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_NORMAL);
#endif // ENABLE_DEBUG
    if (result != 0) {
        isc_throw(isc::InvalidOperation, std::strerror(result));
    }

    auto_ptr<Impl> impl(new Impl);
    result = pthread_mutex_init(&impl->mutex, &attributes);
    switch (result) {
        case 0: // All 0K
            impl_ = impl.release();
            break;
        case ENOMEM:
        case EAGAIN:
            throw std::bad_alloc();
        default:
            isc_throw(isc::InvalidOperation, std::strerror(result));
    }
}

Mutex::~Mutex() {
    if (impl_ != NULL) {
        const int result = pthread_mutex_destroy(&impl_->mutex);

#ifdef ENABLE_DEBUG
        const bool locked = impl_->locked_count != 0;
#endif // ENABLE_DEBUG

        delete impl_;
        // We don't want to throw from the destructor. Also, if this ever
        // fails, something is really screwed up a lot.
        assert(result == 0);

#ifdef ENABLE_DEBUG
        // We should not try to destroy a locked mutex, bad threaded monsters
        // could get loose if we ever do and it is also forbidden by pthreads.

        // This should not be possible to happen, since the
        // pthread_mutex_destroy should check for it already. But it seems
        // there are systems that don't check it.
        assert(!locked);
#endif // ENABLE_DEBUG
    }
}

#ifdef ENABLE_DEBUG

void
Mutex::postLockAction() {
    assert(impl_->locked_count == 0);
    ++impl_->locked_count;
}

void
Mutex::preUnlockAction(bool throw_ok) {
    if (impl_->locked_count == 0) {
        if (throw_ok) {
            isc_throw(isc::InvalidOperation,
                      "Unlock attempt for unlocked mutex");
        } else {
            assert(false);
        }
    }
    --impl_->locked_count;
}

bool
Mutex::locked() const {
    return (impl_->locked_count != 0);
}

#endif // ENABLE_DEBUG

void
Mutex::lock() {
    assert(impl_ != NULL);
    const int result = pthread_mutex_lock(&impl_->mutex);
    if (result != 0) {
        isc_throw(isc::InvalidOperation, std::strerror(result));
    }
#ifdef ENABLE_DEBUG
    postLockAction();           // Only in debug mode
#endif // ENABLE_DEBUG
}

bool
Mutex::tryLock() {
    assert(impl_ != NULL);
    const int result = pthread_mutex_trylock(&impl_->mutex);
    // In the case of pthread_mutex_trylock(), if it is called on a
    // locked mutex from the same thread, some platforms (such as fedora
    // and debian) return EBUSY whereas others (such as centos 5) return
    // EDEADLK. We return false and don't pass the lock attempt in both
    // cases.
    if (result == EBUSY || result == EDEADLK) {
        return (false);
    } else if (result != 0) {
        isc_throw(isc::InvalidOperation, std::strerror(result));
    }
#ifdef ENABLE_DEBUG
    postLockAction();           // Only in debug mode
#endif // ENABLE_DEBUG
    return (true);
}

void
Mutex::unlock() {
    assert(impl_ != NULL);
#ifdef ENABLE_DEBUG
    preUnlockAction(false);     // Only in debug mode.  Ensure no throw.
#endif // ENABLE_DEBUG
    const int result = pthread_mutex_unlock(&impl_->mutex);
    assert(result == 0); // This should never be possible
}

class CondVar::Impl {
public:
    Impl() {
        const int result = pthread_cond_init(&cond_, NULL);
        if (result != 0) {
            isc_throw(isc::Unexpected, "pthread_cond_init failed: "
                      << std::strerror(result));
        }
    }
    ~Impl() {
        const int result = pthread_cond_destroy(&cond_);

        // This can happen if we try to destroy cond_ while some other thread
        // is waiting on it.  assert() may be too strong for such a case,
        // but we cannot safely destroy cond_ anyway.  In order to avoid
        // throwing from a destructor we simply let the process die.
        assert(result == 0);
    }

    // For convenience allow the main class to access this directly.
    pthread_cond_t cond_;
};

CondVar::CondVar() : impl_(new Impl)
{}

CondVar::~CondVar() {
    delete impl_;
}

void
CondVar::wait(Mutex& mutex) {
#ifdef ENABLE_DEBUG
    mutex.preUnlockAction(true);    // Only in debug mode
    const int result = pthread_cond_wait(&impl_->cond_, &mutex.impl_->mutex);
    mutex.postLockAction();     // Only in debug mode
#else
    const int result = pthread_cond_wait(&impl_->cond_, &mutex.impl_->mutex);
#endif
    // pthread_cond_wait should normally succeed unless mutex is completely
    // broken.
    if (result != 0) {
        isc_throw(isc::BadValue, "pthread_cond_wait failed unexpectedly: " <<
                  std::strerror(result));
    }
}

void
CondVar::signal() {
    const int result = pthread_cond_signal(&impl_->cond_);

    // pthread_cond_signal() can only fail when if cond_ is invalid.  It
    //should be impossible as long as this is a valid CondVar object.
    assert(result == 0);
}

}
}
}