• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "perfetto/base/thread_checker.h"
18 
19 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
20 #include <Windows.h>
21 #endif
22 
23 namespace perfetto {
24 namespace base {
25 
26 namespace {
27 constexpr ThreadID kDetached{};
28 
CurrentThreadId()29 ThreadID CurrentThreadId() {
30 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
31   return ::GetCurrentThreadId();
32 #else
33   return pthread_self();
34 #endif
35 }
36 }  // namespace
37 
ThreadChecker()38 ThreadChecker::ThreadChecker() {
39   thread_id_.store(CurrentThreadId());
40 }
41 
42 ThreadChecker::~ThreadChecker() = default;
43 
ThreadChecker(const ThreadChecker & other)44 ThreadChecker::ThreadChecker(const ThreadChecker& other) {
45   thread_id_ = other.thread_id_.load();
46 }
47 
operator =(const ThreadChecker & other)48 ThreadChecker& ThreadChecker::operator=(const ThreadChecker& other) {
49   thread_id_ = other.thread_id_.load();
50   return *this;
51 }
52 
CalledOnValidThread() const53 bool ThreadChecker::CalledOnValidThread() const {
54   auto self = CurrentThreadId();
55 
56   // Will re-attach if previously detached using DetachFromThread().
57   auto prev_value = kDetached;
58   if (thread_id_.compare_exchange_strong(prev_value, self))
59     return true;
60   return prev_value == self;
61 }
62 
DetachFromThread()63 void ThreadChecker::DetachFromThread() {
64   thread_id_.store(kDetached);
65 }
66 
67 }  // namespace base
68 }  // namespace perfetto
69