/Users/deen/code/yugabyte-db/src/yb/util/cross_thread_mutex.h
Line | Count | Source |
1 | | // Copyright (c) YugaByte, Inc. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
4 | | // in compliance with the License. You may obtain a copy of the License at |
5 | | // |
6 | | // http://www.apache.org/licenses/LICENSE-2.0 |
7 | | // |
8 | | // Unless required by applicable law or agreed to in writing, software distributed under the License |
9 | | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
10 | | // or implied. See the License for the specific language governing permissions and limitations |
11 | | // under the License. |
12 | | // |
13 | | |
14 | | #ifndef YB_UTIL_CROSS_THREAD_MUTEX_H_ |
15 | | #define YB_UTIL_CROSS_THREAD_MUTEX_H_ |
16 | | |
17 | | #include <condition_variable> |
18 | | |
19 | | namespace yb { |
20 | | |
21 | | // This is a wrapper around std::mutex which can be locked and unlocked from different threads. |
22 | | class CrossThreadMutex { |
23 | | public: |
24 | | void lock(); |
25 | | |
26 | | void unlock(); |
27 | | |
28 | | template <class Rep, class Period> |
29 | | bool try_lock_for(const std::chrono::duration<Rep, Period>& duration); |
30 | | |
31 | | template <class Clock, class Duration> |
32 | | bool try_lock_until(const std::chrono::time_point<Clock, Duration>& deadline); |
33 | | |
34 | | private: |
35 | 658k | auto NotLockedLambda() { |
36 | 828k | return [this] { return !is_locked_; }; |
37 | 658k | } |
38 | | |
39 | | std::mutex mutex_; |
40 | | std::condition_variable condition_variable_; |
41 | | bool is_locked_ = false; |
42 | | }; |
43 | | |
44 | | template <class Rep, class Period> |
45 | | bool CrossThreadMutex::try_lock_for(const std::chrono::duration<Rep, Period>& duration) { |
46 | | std::unique_lock<std::mutex> lock(mutex_); |
47 | | if (!condition_variable_.wait_for(lock, duration, NotLockedLambda())) { |
48 | | return false; |
49 | | } |
50 | | is_locked_ = true; |
51 | | return true; |
52 | | } |
53 | | |
54 | | template <class Clock, class Duration> |
55 | 658k | bool CrossThreadMutex::try_lock_until(const std::chrono::time_point<Clock, Duration>& deadline) { |
56 | 658k | std::unique_lock<std::mutex> lock(mutex_); |
57 | 658k | if (!condition_variable_.wait_until(lock, deadline, NotLockedLambda())) { |
58 | 168k | return false; |
59 | 168k | } |
60 | 490k | is_locked_ = true; |
61 | 490k | return true; |
62 | 490k | } |
63 | | |
64 | | } // namespace yb |
65 | | |
66 | | #endif // YB_UTIL_CROSS_THREAD_MUTEX_H_ |