blob: 079714c7c4f2aa9944624e49902ea86477519456 [file] [log] [blame]
Primiano Tucci4f9b6d72017-12-05 20:59:16 +00001/*
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
19namespace perfetto {
20namespace base {
21
22namespace {
23constexpr pthread_t kDetached = 0;
24} // namespace
25
26ThreadChecker::ThreadChecker() {
27 thread_id_.store(pthread_self());
28}
29
30ThreadChecker::~ThreadChecker() = default;
31
32ThreadChecker::ThreadChecker(const ThreadChecker& other) {
33 thread_id_ = other.thread_id_.load();
34}
35
36ThreadChecker& ThreadChecker::operator=(const ThreadChecker& other) {
37 thread_id_ = other.thread_id_.load();
38 return *this;
39}
40
41bool 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
51void ThreadChecker::DetachFromThread() {
52 thread_id_.store(kDetached);
53}
54
55} // namespace base
56} // namespace perfetto