summaryrefslogtreecommitdiff
path: root/chromium/base/task_scheduler/scheduler_lock.h
blob: c969eb19c07f121f80d3a9c312a4ed88bfdf6a9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_TASK_SCHEDULER_SCHEDULER_LOCK_H
#define BASE_TASK_SCHEDULER_SCHEDULER_LOCK_H

#include <memory>

#include "base/base_export.h"
#include "base/macros.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "base/task_scheduler/scheduler_lock_impl.h"

namespace base {
namespace internal {

// SchedulerLock should be used anywhere a lock would be used in the scheduler.
// When DCHECK_IS_ON(), lock checking occurs. Otherwise, SchedulerLock is
// equivalent to base::Lock.
//
// The shape of SchedulerLock is as follows:
// SchedulerLock()
//     Default constructor, no predecessor lock.
//     DCHECKs
//         On Acquisition if any scheduler lock is acquired on this thread.
//
// SchedulerLock(const SchedulerLock* predecessor)
//     Constructor that specifies an allowed predecessor for that lock.
//     DCHECKs
//         On Construction if |predecessor| forms a predecessor lock cycle.
//         On Acquisition if the previous lock acquired on the thread is not
//             |predecessor|. Okay if there was no previous lock acquired.
//
// void Acquire()
//     Acquires the lock.
//
// void Release()
//     Releases the lock.
//
// void AssertAcquired().
//     DCHECKs if the lock is not acquired.
//
// std::unique_ptr<ConditionVariable> CreateConditionVariable()
//     Creates a condition variable using this as a lock.

#if DCHECK_IS_ON()
class SchedulerLock : public SchedulerLockImpl {
 public:
  SchedulerLock() = default;
  explicit SchedulerLock(const SchedulerLock* predecessor)
      : SchedulerLockImpl(predecessor) {}
};
#else  // DCHECK_IS_ON()
class SchedulerLock : public Lock {
 public:
  SchedulerLock() = default;
  explicit SchedulerLock(const SchedulerLock*) {}

  std::unique_ptr<ConditionVariable> CreateConditionVariable() {
    return std::unique_ptr<ConditionVariable>(new ConditionVariable(this));
  }
};
#endif  // DCHECK_IS_ON()

// Provides the same functionality as base::AutoLock for SchedulerLock.
class AutoSchedulerLock {
 public:
  explicit AutoSchedulerLock(SchedulerLock& lock) : lock_(lock) {
    lock_.Acquire();
  }

  ~AutoSchedulerLock() {
    lock_.AssertAcquired();
    lock_.Release();
  }

 private:
  SchedulerLock& lock_;

  DISALLOW_COPY_AND_ASSIGN(AutoSchedulerLock);
};

}  // namespace internal
}  // namespace base

#endif  // BASE_TASK_SCHEDULER_SCHEDULER_LOCK_H