userver: userver/engine/mutex.hpp Source File
Loading...
Searching...
No Matches
mutex.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/mutex.hpp
4/// @brief @copybrief engine::Mutex
5
6#include <atomic>
7#include <chrono>
8#include <mutex> // for std locks
9
10#include <userver/engine/deadline.hpp>
11#include <userver/engine/impl/wait_list_fwd.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace engine {
16
17/// @ingroup userver_concurrency
18///
19/// @brief std::mutex replacement for asynchronous tasks
20///
21/// ## Example usage:
22///
23/// @snippet engine/mutex_test.cpp Sample engine::Mutex usage
24///
25/// @see @ref scripts/docs/en/userver/synchronization.md
26class Mutex final {
27 public:
28 Mutex();
29 ~Mutex();
30
31 Mutex(const Mutex&) = delete;
32 Mutex(Mutex&&) = delete;
33 Mutex& operator=(const Mutex&) = delete;
34 Mutex& operator=(Mutex&&) = delete;
35
36 /// Locks the mutex. Blocks current coroutine if the mutex is locked by
37 /// another coroutine.
38 /// @note the behaviour is undefined if a coroutine tries to lock a mutex
39 /// which is already locked by the current coroutine.
40 /// @note the method waits for the mutex even if the current task is
41 /// cancelled.
42 void lock();
43
44 /// Unlocks the mutex. The mutex must be locked by the current coroutine.
45 /// @note the behaviour is undefined if a coroutine tries to unlock a mutex
46 /// which is not locked or is locked by another coroutine
47 /// @note the order of coroutines to unblock is unspecified. Any code assuming
48 /// any specific order (e.g. FIFO) is incorrect and must be fixed.
49 void unlock();
50
51 bool try_lock();
52
53 template <typename Rep, typename Period>
54 bool try_lock_for(const std::chrono::duration<Rep, Period>&);
55
56 template <typename Clock, typename Duration>
57 bool try_lock_until(const std::chrono::time_point<Clock, Duration>&);
58
59 bool try_lock_until(Deadline deadline);
60
61 private:
62 class Impl;
63
64 utils::FastPimpl<Impl, 96, alignof(void*)> impl_;
65};
66
67template <typename Rep, typename Period>
68bool Mutex::try_lock_for(const std::chrono::duration<Rep, Period>& duration) {
69 return try_lock_until(Deadline::FromDuration(duration));
70}
71
72template <typename Clock, typename Duration>
73bool Mutex::try_lock_until(
74 const std::chrono::time_point<Clock, Duration>& until) {
75 return try_lock_until(Deadline::FromTimePoint(until));
76}
77
78} // namespace engine
79
80USERVER_NAMESPACE_END