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 namespace perfetto { 20 namespace base { 21 22 namespace { 23 constexpr pthread_t kDetached = 0; 24 } // namespace 25 26 ThreadChecker::ThreadChecker() { 27 thread_id_.store(pthread_self()); 28 } 29 30 ThreadChecker::~ThreadChecker() = default; 31 32 ThreadChecker::ThreadChecker(const ThreadChecker& other) { 33 thread_id_ = other.thread_id_.load(); 34 } 35 36 ThreadChecker& ThreadChecker::operator=(const ThreadChecker& other) { 37 thread_id_ = other.thread_id_.load(); 38 return *this; 39 } 40 41 bool ThreadChecker::CalledOnValidThread() const { 42 pthread_t self = pthread_self(); 43 44 // Will re-attach if previously detached using DetachFromThread(). 45 pthread_t prev_value = kDetached; 46 if (thread_id_.compare_exchange_strong(prev_value, self)) 47 return true; 48 return prev_value == self; 49 } 50 51 void ThreadChecker::DetachFromThread() { 52 thread_id_.store(kDetached); 53 } 54 55 } // namespace base 56 } // namespace perfetto 57