YugabyteDB (2.13.1.0-b60, 21121d69985fbf76aa6958d8f04a9bfa936293b5)

Coverage Report

Created: 2022-03-22 16:43

/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
775k
  auto NotLockedLambda() {
36
794k
    return [this] { return !is_locked_; };
37
775k
  }
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
775k
bool CrossThreadMutex::try_lock_until(const std::chrono::time_point<Clock, Duration>& deadline) {
56
775k
  std::unique_lock<std::mutex> lock(mutex_);
57
775k
  if (!condition_variable_.wait_until(lock, deadline, NotLockedLambda())) {
58
17.6k
    return false;
59
17.6k
  }
60
757k
  is_locked_ = true;
61
757k
  return true;
62
775k
}
63
64
}  // namespace yb
65
66
#endif  // YB_UTIL_CROSS_THREAD_MUTEX_H_