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 explicit mutex(pthread_mutex_t& mutex_p) : _mutex(mutex_p)
35 /* "Not copyable" and "not moveable" Mutex requirements. */
36 mutex(mutex const&) = delete;
37 mutex(mutex&&) = delete;
38 mutex& operator=(mutex const&) = delete;
39 mutex& operator=(mutex&&) = delete;
43 if (pthread_mutex_lock(&_mutex) != 0) {
44 LTTNG_THROW_POSIX("Failed to lock mutex", errno);
50 const auto ret = pthread_mutex_trylock(&_mutex);
54 } else if (errno == EBUSY || errno == EAGAIN) {
57 LTTNG_THROW_POSIX("Failed to try to lock mutex", errno);
63 if (pthread_mutex_unlock(&_mutex) != 0) {
65 * Unlock cannot throw as it is called as part of lock_guard's destructor.
72 pthread_mutex_t& _mutex;
74 } /* namespace details */
77 * Provides the basic concept of std::lock_guard for posix mutexes.
79 * `lock` is held for the duration of lock_guard's lifetime.
83 explicit lock_guard(pthread_mutex_t& mutex) : _mutex(mutex), _guard(_mutex)
87 ~lock_guard() = default;
89 lock_guard(const lock_guard&) = delete;
90 lock_guard(lock_guard&&) = delete;
91 lock_guard& operator=(const lock_guard&) = delete;
92 lock_guard& operator=(lock_guard&&) = delete;
95 details::mutex _mutex;
96 std::lock_guard<details::mutex> _guard;
99 } /* namespace pthread */
100 } /* namespace lttng */
102 #endif /* LTTNG_PTHREAD_LOCK_H */