userver: userver/engine/shared_mutex.hpp Source File
Loading...
Searching...
No Matches
shared_mutex.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/shared_mutex.hpp
4/// @brief @copybrief engine::SharedMutex
5
6#include <userver/engine/condition_variable.hpp>
7#include <userver/engine/impl/actor.hpp>
8#include <userver/engine/mutex.hpp>
9#include <userver/engine/semaphore.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace engine {
14
15/// @ingroup userver_concurrency
16///
17/// @brief std::shared_mutex replacement for asynchronous tasks.
18///
19/// Ignores task cancellations (succeeds even if the current task is cancelled).
20///
21/// Writers (unique locks) have priority over readers (shared locks),
22/// thus new shared lock waits for the pending writes to finish, which in turn
23/// waits for existing existing shared locks to unlock first.
24///
25/// ## Example usage:
26///
27/// @snippet core/src/engine/shared_mutex_test.cpp Sample engine::SharedMutex usage
28///
29/// @see @ref scripts/docs/en/userver/synchronization.md
30class SharedMutex final {
31public:
32 SharedMutex();
33 ~SharedMutex();
34
35 SharedMutex(const SharedMutex&) = delete;
36 SharedMutex(SharedMutex&&) = delete;
37 SharedMutex& operator=(const SharedMutex&) = delete;
38 SharedMutex& operator=(SharedMutex&&) = delete;
39
40 /// Locks the mutex for unique ownership. Blocks current task if the
41 /// mutex is locked by another task for reading or writing.
42 ///
43 /// @note The method waits for the mutex even if the current task is cancelled.
44 void lock();
45
46 /// Unlocks the mutex for unique ownership. Before calling this method the
47 /// the mutex should be locked for unique ownership by current task.
48 ///
49 /// @note the order of tasks to unblock is unspecified. Any code assuming
50 /// any specific order (e.g. FIFO) is incorrect and should be fixed.
51 void unlock();
52
53 /// Tries to lock the mutex for unique ownership without blocking the task, returns true if succeeded.
54 [[nodiscard]] bool try_lock();
55
56 /// Tries to lock the mutex for unique ownership in specified duration.
57 /// Blocks current task if the mutex is locked by another task up to the provided duration.
58 ///
59 /// @returns true if the locking succeeded
60 template <typename Rep, typename Period>
61 [[nodiscard]] bool try_lock_for(const std::chrono::duration<Rep, Period>&);
62
63 /// Tries to lock the mutex for unique ownership till specified time point.
64 /// Blocks current task if the mutex is locked by another task up to the provided duration.
65 ///
66 /// @returns true if the locking succeeded
67 template <typename Clock, typename Duration>
68 [[nodiscard]] bool try_lock_until(const std::chrono::time_point<Clock, Duration>&);
69
70 /// @overload
71 [[nodiscard]] bool try_lock_until(Deadline deadline);
72
73 /// Locks the mutex for shared access. Blocks the current task if the mutex
74 /// is already locked by another task for writing or if there are writers waiting.
75 ///
76 /// @note The method waits for the mutex even if the current task is cancelled.
78
79 /// Unlocks the mutex for shared ownership. Before calling this method the
80 /// mutex should be locked for shared ownership by current task.
81 ///
82 /// @note the order of tasks to unblock is unspecified. Any code assuming
83 /// any specific order (e.g. FIFO) is incorrect and should be fixed.
85
86 /// Atomically converts the ownership from exclusive to shared.
87 ///
88 /// @note Does not block.
90
91 /// Tries to lock the mutex for shared ownership without blocking the
92 /// task, returns true if succeeded.
93 [[nodiscard]] bool try_lock_shared();
94
95 /// Tries to lock the mutex for shared ownership in specified duration.
96 /// Blocks current task if the mutex is locked by another task up to the provided duration.
97 ///
98 /// @returns true if the locking succeeded
99 template <typename Rep, typename Period>
100 [[nodiscard]] bool try_lock_shared_for(const std::chrono::duration<Rep, Period>&);
101
102 /// Tries to lock the mutex for shared ownership till specified time point.
103 /// Blocks current task if the mutex is locked by another task up to the provided duration.
104 ///
105 /// @returns true if the locking succeeded
106 template <typename Clock, typename Duration>
107 [[nodiscard]] bool try_lock_shared_until(const std::chrono::time_point<Clock, Duration>&);
108
109 /// @overload
110 [[nodiscard]] bool try_lock_shared_until(Deadline deadline);
111
112private:
113 bool HasRegisteredWriter() const noexcept;
114
115 bool WaitForNoRegisteredWriters(Deadline deadline);
116
117 enum class DeadlockDetectorTrackingStatus : std::uint8_t { kUntracked, kTracked };
118
119 void UnregisterWriter(DeadlockDetectorTrackingStatus tracking_status);
120
121 /* Semaphore can be get by 1 or by SIZE_MAX.
122 * 1 = reader, SIZE_MAX = writer.
123 *
124 * Three possible cases:
125 * 1) semaphore is free
126 * 2) there are readers in critical section (any count)
127 * 3) there is a single writer in critical section
128 */
129 Semaphore semaphore_;
130
131 /* Readers don't try to hold semaphore_ if there is at least one
132 * registered writer => writers don't starve.
133 */
134 std::atomic<ssize_t> registered_writers_count_;
135 Mutex registered_writers_count_mutex_;
136 ConditionVariable registered_writers_count_cv_;
137
138 struct RegisteredWritersActor final : public impl::deadlock_detector::Actor {
139 utils::StringLiteral GetActorType() const override;
140 };
141
142 struct MutexActor final : public impl::deadlock_detector::Actor {
143 utils::StringLiteral GetActorType() const override;
144 };
145
146 // An identity actor for registered (waiting and active) writers.
147 // Used to track dependencies between shared readers and registered writers in deadlock detector.
148 // While there are registered writers owning this actor all shared readers will wait for it.
149 RegisteredWritersActor registered_writers_actor_;
150 // An identity actor for the mutex itself.
151 // Used to track ownership of the mutex and waits on the mutex in deadlock detector.
152 // While there is an active writer or a set of active shared readers owning this actor
153 // other writers will waiting for it.
154 MutexActor mutex_actor_;
155};
156
157template <typename Rep, typename Period>
158bool SharedMutex::try_lock_for(const std::chrono::duration<Rep, Period>& duration) {
159 return try_lock_until(Deadline::FromDuration(duration));
160}
161
162template <typename Rep, typename Period>
163bool SharedMutex::try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration) {
164 return try_lock_shared_until(Deadline::FromDuration(duration));
165}
166
167template <typename Clock, typename Duration>
168bool SharedMutex::try_lock_until(const std::chrono::time_point<Clock, Duration>& until) {
169 return try_lock_until(Deadline::FromTimePoint(until));
170}
171
172template <typename Clock, typename Duration>
173bool SharedMutex::try_lock_shared_until(const std::chrono::time_point<Clock, Duration>& until) {
174 return try_lock_shared_until(Deadline::FromTimePoint(until));
175}
176
177} // namespace engine
178
179USERVER_NAMESPACE_END