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_NON_THREAD_SAFE_H_ 6 #define BASE_THREADING_NON_THREAD_SAFE_H_ 7 8 // Classes deriving from NonThreadSafe may need to suppress MSVC warning 4275: 9 // non dll-interface class 'Bar' used as base for dll-interface class 'Foo'. 10 // There is a specific macro to do it: NON_EXPORTED_BASE(), defined in 11 // compiler_specific.h 12 #include "base/compiler_specific.h" 13 #include "base/logging.h" 14 #include "base/threading/non_thread_safe_impl.h" 15 16 namespace base { 17 18 // Do nothing implementation of NonThreadSafe, for release mode. 19 // 20 // Note: You should almost always use the NonThreadSafe class to get 21 // the right version of the class for your build configuration. 22 class NonThreadSafeDoNothing { 23 public: CalledOnValidThread()24 bool CalledOnValidThread() const { 25 return true; 26 } 27 28 protected: ~NonThreadSafeDoNothing()29 ~NonThreadSafeDoNothing() {} DetachFromThread()30 void DetachFromThread() {} 31 }; 32 33 // NonThreadSafe is a helper class used to help verify that methods of a 34 // class are called from the same thread. One can inherit from this class 35 // and use CalledOnValidThread() to verify. 36 // 37 // This is intended to be used with classes that appear to be thread safe, but 38 // aren't. For example, a service or a singleton like the preferences system. 39 // 40 // Example: 41 // class MyClass : public base::NonThreadSafe { 42 // public: 43 // void Foo() { 44 // DCHECK(CalledOnValidThread()); 45 // ... (do stuff) ... 46 // } 47 // } 48 // 49 // Note that base::ThreadChecker offers identical functionality to 50 // NonThreadSafe, but does not require inheritance. In general, it is preferable 51 // to have a base::ThreadChecker as a member, rather than inherit from 52 // NonThreadSafe. For more details about when to choose one over the other, see 53 // the documentation for base::ThreadChecker. 54 #if DCHECK_IS_ON() 55 typedef NonThreadSafeImpl NonThreadSafe; 56 #else 57 typedef NonThreadSafeDoNothing NonThreadSafe; 58 #endif // DCHECK_IS_ON() 59 60 } // namespace base 61 62 #endif // BASE_THREADING_NON_THREAD_SAFE_H_ 63