librf

mutex_v1.h
1 #pragma once
2
3 namespace resumef
4 {
5 namespace detail
6 {
7 struct mutex_impl;
8 typedef ::resumef::detail::_awaker<mutex_impl> mutex_awaker;
9 typedef std::shared_ptr<mutex_awaker> mutex_awaker_ptr;
10
11 struct mutex_impl : public std::enable_shared_from_this<mutex_impl>
12 {
13 private:
14 //typedef spinlock lock_type;
15 typedef std::recursive_mutex lock_type;
16
17 std::list<mutex_awaker_ptr> _awakes;
18 mutex_awaker_ptr _owner;
19 lock_type _lock;
20 public:
21 mutex_impl();
22
23 //如果已经触发了awaker,则返回true
24 bool lock_(const mutex_awaker_ptr& awaker);
25 bool try_lock_(const mutex_awaker_ptr& awaker);
26 void unlock();
27
28 template<class callee_t, class dummy_t = std::enable_if<!std::is_same<std::remove_cv_t<callee_t>, mutex_awaker_ptr>::value>>
29 decltype(auto) lock(callee_t&& awaker, dummy_t* dummy_ = nullptr)
30 {
31 (void)dummy_;
32 return lock_(std::make_shared<mutex_awaker>(std::forward<callee_t>(awaker)));
33 }
34
35 private:
36 mutex_impl(const mutex_impl&) = delete;
37 mutex_impl(mutex_impl&&) = delete;
38 mutex_impl& operator = (const mutex_impl&) = delete;
39 mutex_impl& operator = (mutex_impl&&) = delete;
40 };
41 }
42
43 namespace mutex_v1
44 {
45 struct mutex_t
46 {
47 typedef std::shared_ptr<detail::mutex_impl> lock_impl_ptr;
48 typedef std::weak_ptr<detail::mutex_impl> lock_impl_wptr;
49 typedef std::chrono::system_clock clock_type;
50 private:
51 lock_impl_ptr _locker;
52 public:
53 mutex_t();
54
55 void unlock() const
56 {
57 _locker->unlock();
58 }
59
60
61 future_t<bool> lock() const;
62 bool try_lock() const;
63
64 /*
65 template<class _Rep, class _Period>
66 awaitable_t<bool>
67 try_lock_for(const std::chrono::duration<_Rep, _Period> & dt) const
68 {
69 return try_lock_for_(std::chrono::duration_cast<clock_type::duration>(dt));
70 }
71 template<class _Clock, class _Duration>
72 awaitable_t<bool>
73 try_lock_until(const std::chrono::time_point<_Clock, _Duration> & tp) const
74 {
75 return try_lock_until_(std::chrono::time_point_cast<clock_type::duration>(tp));
76 }
77 */
78
79
80 mutex_t(const mutex_t&) = default;
81 mutex_t(mutex_t&&) = default;
82 mutex_t& operator = (const mutex_t&) = default;
83 mutex_t& operator = (mutex_t&&) = default;
84 private:
85 inline future_t<bool> try_lock_for_(const clock_type::duration& dt) const
86 {
87 return try_lock_until_(clock_type::now() + dt);
88 }
89 future_t<bool> try_lock_until_(const clock_type::time_point& tp) const;
90 };
91 }
92 }