blob: c723dbe5fb5da774bab825b48813ff9ea0d2de7d [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
Bruce Dawson2af6ef72018-05-01 15:28:39 +010019#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
20#include <Windows.h>
21#endif
22
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000023namespace perfetto {
24namespace base {
25
26namespace {
Ali Ijaz Sheikhe63537c2018-05-02 13:16:25 -070027constexpr ThreadID kDetached{};
Bruce Dawson2af6ef72018-05-01 15:28:39 +010028
29ThreadID CurrentThreadId() {
30#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
31 return ::GetCurrentThreadId();
32#else
33 return pthread_self();
34#endif
35}
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000036} // namespace
37
38ThreadChecker::ThreadChecker() {
Bruce Dawson2af6ef72018-05-01 15:28:39 +010039 thread_id_.store(CurrentThreadId());
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000040}
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 {
Bruce Dawson2af6ef72018-05-01 15:28:39 +010054 auto self = CurrentThreadId();
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000055
56 // Will re-attach if previously detached using DetachFromThread().
Bruce Dawson2af6ef72018-05-01 15:28:39 +010057 auto prev_value = kDetached;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000058 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