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