1 // Copyright (c) 2012 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 8 #include "base/logging.h" 9 #include "base/threading/thread_checker_impl.h" 10 11 // Apart from debug builds, we also enable the thread checker in 12 // builds with DCHECK_ALWAYS_ON so that trybots and waterfall bots 13 // with this define will get the same level of thread checking as 14 // debug bots. 15 #if DCHECK_IS_ON() 16 #define ENABLE_THREAD_CHECKER 1 17 #else 18 #define ENABLE_THREAD_CHECKER 0 19 #endif 20 21 namespace base { 22 23 // Do nothing implementation, for use in release mode. 24 // 25 // Note: You should almost always use the ThreadChecker class to get the 26 // right version for your build configuration. 27 class ThreadCheckerDoNothing { 28 public: 29 bool CalledOnValidThread() const WARN_UNUSED_RESULT { 30 return true; 31 } 32 33 void DetachFromThread() {} 34 }; 35 36 // ThreadChecker is a helper class used to help verify that some methods of a 37 // class are called from the same thread. It provides identical functionality to 38 // base::NonThreadSafe, but it is meant to be held as a member variable, rather 39 // than inherited from base::NonThreadSafe. 40 // 41 // While inheriting from base::NonThreadSafe may give a clear indication about 42 // the thread-safety of a class, it may also lead to violations of the style 43 // guide with regard to multiple inheritance. The choice between having a 44 // ThreadChecker member and inheriting from base::NonThreadSafe should be based 45 // on whether: 46 // - Derived classes need to know the thread they belong to, as opposed to 47 // having that functionality fully encapsulated in the base class. 48 // - Derived classes should be able to reassign the base class to another 49 // thread, via DetachFromThread. 50 // 51 // If neither of these are true, then having a ThreadChecker member and calling 52 // CalledOnValidThread is the preferable solution. 53 // 54 // Example: 55 // class MyClass { 56 // public: 57 // void Foo() { 58 // DCHECK(thread_checker_.CalledOnValidThread()); 59 // ... (do stuff) ... 60 // } 61 // 62 // private: 63 // ThreadChecker thread_checker_; 64 // } 65 // 66 // In Release mode, CalledOnValidThread will always return true. 67 #if ENABLE_THREAD_CHECKER 68 class ThreadChecker : public ThreadCheckerImpl { 69 }; 70 #else 71 class ThreadChecker : public ThreadCheckerDoNothing { 72 }; 73 #endif // ENABLE_THREAD_CHECKER 74 75 #undef ENABLE_THREAD_CHECKER 76 77 } // namespace base 78 79 #endif // BASE_THREADING_THREAD_CHECKER_H_ 80