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) {
60 LTTNG_THROW_POSIX("Failed to unlock mutex", errno);
65 pthread_mutex_t& _mutex;
67 } /* namespace details */
70 * Provides the basic concept of std::lock_guard for posix mutexes.
72 * `lock` is held for the duration of lock_guard's lifetime.
76 lock_guard(pthread_mutex_t& mutex) : _mutex{mutex}, _guard(_mutex)
80 lock_guard(const lock_guard &) = delete;
83 details::mutex _mutex;
84 std::lock_guard<details::mutex> _guard;
87 } /* namespace pthread */
88 } /* namespace lttng */
90 #endif /* LTTNG_PTHREAD_LOCK_H */