2 * Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 * SPDX-License-Identifier: LGPL-2.1-only
8 #ifndef LTTNG_PTHREAD_LOCK_H
9 #define LTTNG_PTHREAD_LOCK_H
11 #include <common/exception.hpp>
21 * Class wrapping pthread mutexes and satisfying the Mutex named requirements, except
22 * for the "Default Constructible" requirement. The class is not default-constructible since the
23 * intention is to ease the transition of existing C-code using pthread mutexes to idiomatic C++.
25 * New code should use std::mutex.
29 mutex(pthread_mutex_t& mutex_p) : _mutex{mutex_p}
33 /* "Not copyable" and "not moveable" Mutex requirements. */
34 mutex(mutex const &) = delete;
35 mutex &operator=(mutex const &) = delete;
39 if (pthread_mutex_lock(&_mutex) != 0) {
40 LTTNG_THROW_POSIX("Failed to lock mutex", errno);
46 const auto ret = pthread_mutex_trylock(&_mutex);
50 } else if (errno == EBUSY || errno == EAGAIN) {
53 LTTNG_THROW_POSIX("Failed to try to lock mutex", errno);
59 if (pthread_mutex_unlock(&_mutex) != 0) {
61 * Unlock cannot throw as it is called as part of lock_guard's destructor.
68 pthread_mutex_t& _mutex;
70 } /* namespace details */
73 * Provides the basic concept of std::lock_guard for posix mutexes.
75 * `lock` is held for the duration of lock_guard's lifetime.
79 lock_guard(pthread_mutex_t& mutex) : _mutex{mutex}, _guard(_mutex)
83 lock_guard(const lock_guard &) = delete;
86 details::mutex _mutex;
87 std::lock_guard<details::mutex> _guard;
90 } /* namespace pthread */
91 } /* namespace lttng */
93 #endif /* LTTNG_PTHREAD_LOCK_H */