blob: 501abbb6b1a514b47d20b05ce5b2bc31d7b8b39d [file] [log] [blame]
Kaido Kert56d7c4e2024-04-13 12:59:27 -07001/*
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/ext/base/thread_checker.h"
18
19#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
20#include <Windows.h>
21#endif
22
23namespace perfetto {
24namespace base {
25
26namespace {
27constexpr ThreadID kDetached{};
28
29ThreadID CurrentThreadId() {
30#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
31 return ::GetCurrentThreadId();
32#else
33 return pthread_self();
34#endif
35}
36} // namespace
37
38ThreadChecker::ThreadChecker() {
39 thread_id_.store(CurrentThreadId());
40}
41
42ThreadChecker::~ThreadChecker() = default;
43
44ThreadChecker::ThreadChecker(const ThreadChecker& other) {
45 thread_id_ = other.thread_id_.load();
46}
47
48ThreadChecker& ThreadChecker::operator=(const ThreadChecker& other) {
49 thread_id_ = other.thread_id_.load();
50 return *this;
51}
52
53bool 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
63void ThreadChecker::DetachFromThread() {
64 thread_id_.store(kDetached);
65}
66
67} // namespace base
68} // namespace perfetto