chromium之non_thread_safe

先看看介绍

// A helper class used to help verify that methods of a class are
// called from the same thread.  One can inherit from this class and use
// CalledOnValidThread() to verify.
//
// This is intended to be used with classes that appear to be thread safe, but
// aren't.  For example, a service or a singleton like the preferences system.
//
// Example:
// class MyClass : public NonThreadSafe {
//  public:
//   void Foo() {
//     DCHECK(CalledOnValidThread());
//     ... (do stuff) ...
//   }
// }
//

线程A创建了MyClass,但是Foo()是非线程安全的函数

因此在Debug模式下,需要检验Foo()是否在线程A内调用

通过如下函数来判断。

CalledOnValidThread()

 

看一下实现,就知道很简单了。

NonThreadSafe::NonThreadSafe()
    : valid_thread_id_(PlatformThread::CurrentId()) {
}

bool NonThreadSafe::CalledOnValidThread() const {
  return valid_thread_id_ == PlatformThread::CurrentId();
}

 

posted on 2018-05-17 21:52  ckelsel  阅读(146)  评论(0编辑  收藏  举报

导航