Home | History | Annotate | Download | only in base
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef INCLUDE_PERFETTO_BASE_THREAD_CHECKER_H_
     18 #define INCLUDE_PERFETTO_BASE_THREAD_CHECKER_H_
     19 
     20 #include "perfetto/base/build_config.h"
     21 
     22 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
     23 #include <pthread.h>
     24 #endif
     25 #include <atomic>
     26 
     27 #include "perfetto/base/export.h"
     28 #include "perfetto/base/logging.h"
     29 #include "perfetto/base/utils.h"
     30 
     31 namespace perfetto {
     32 namespace base {
     33 
     34 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
     35 using ThreadID = unsigned long;
     36 #else
     37 using ThreadID = pthread_t;
     38 #endif
     39 
     40 class PERFETTO_EXPORT ThreadChecker {
     41  public:
     42   ThreadChecker();
     43   ~ThreadChecker();
     44   ThreadChecker(const ThreadChecker&);
     45   ThreadChecker& operator=(const ThreadChecker&);
     46   bool CalledOnValidThread() const PERFETTO_WARN_UNUSED_RESULT;
     47   void DetachFromThread();
     48 
     49  private:
     50   mutable std::atomic<ThreadID> thread_id_;
     51 };
     52 
     53 #if PERFETTO_DCHECK_IS_ON() && !defined(PERFETTO_BUILD_WITH_CHROMIUM)
     54 // TODO(primiano) Use Chromium's thread checker in Chromium.
     55 #define PERFETTO_THREAD_CHECKER(name) base::ThreadChecker name;
     56 #define PERFETTO_DCHECK_THREAD(name) \
     57   PERFETTO_DCHECK((name).CalledOnValidThread())
     58 #define PERFETTO_DETACH_FROM_THREAD(name) (name).DetachFromThread()
     59 #else
     60 #define PERFETTO_THREAD_CHECKER(name)
     61 #define PERFETTO_DCHECK_THREAD(name)
     62 #define PERFETTO_DETACH_FROM_THREAD(name)
     63 #endif  // PERFETTO_DCHECK_IS_ON()
     64 
     65 }  // namespace base
     66 }  // namespace perfetto
     67 
     68 #endif  // INCLUDE_PERFETTO_BASE_THREAD_CHECKER_H_
     69