thread_checker.h revision 3f50c38dc070f4bb515c1b64450dae14f316474e
1// Copyright (c) 2010 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_THREADING_THREAD_CHECKER_H_
6#define BASE_THREADING_THREAD_CHECKER_H_
7#pragma once
8
9#ifndef NDEBUG
10#include "base/lock.h"
11#include "base/threading/platform_thread.h"
12#endif // NDEBUG
13
14namespace base {
15
16// Before using this class, please consider using NonThreadSafe as it
17// makes it much easier to determine the nature of your class.
18//
19// A helper class used to help verify that some methods of a class are
20// called from the same thread.  One can inherit from this class and use
21// CalledOnValidThread() to verify.
22//
23// Inheriting from class indicates that one must be careful when using the class
24// with multiple threads. However, it is up to the class document to indicate
25// how it can be used with threads.
26//
27// Example:
28// class MyClass : public ThreadChecker {
29//  public:
30//   void Foo() {
31//     DCHECK(CalledOnValidThread());
32//     ... (do stuff) ...
33//   }
34// }
35//
36// In Release mode, CalledOnValidThread will always return true.
37//
38#ifndef NDEBUG
39class ThreadChecker {
40 public:
41  ThreadChecker();
42  ~ThreadChecker();
43
44  bool CalledOnValidThread() const;
45
46  // Changes the thread that is checked for in CalledOnValidThread.  This may
47  // be useful when an object may be created on one thread and then used
48  // exclusively on another thread.
49  void DetachFromThread();
50
51 private:
52  void EnsureThreadIdAssigned() const;
53
54  mutable Lock lock_;
55  // This is mutable so that CalledOnValidThread can set it.
56  // It's guarded by |lock_|.
57  mutable PlatformThreadId valid_thread_id_;
58};
59#else
60// Do nothing in release mode.
61class ThreadChecker {
62 public:
63  bool CalledOnValidThread() const {
64    return true;
65  }
66
67  void DetachFromThread() {}
68};
69#endif  // NDEBUG
70
71}  // namespace base
72
73#endif  // BASE_THREADING_THREAD_CHECKER_H_
74