blob: 48478e713132eee97a56d2e95dcbc27dc78f1efa [file] [log] [blame]
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +00001/*
2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11// Borrowed from Chromium's src/base/threading/thread_checker_impl.cc.
12
13#include "webrtc/base/thread_checker_impl.h"
14
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000015#include "webrtc/base/checks.h"
16
17#if defined(WEBRTC_LINUX)
18#include <sys/syscall.h>
19#endif
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000020
21namespace rtc {
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000022namespace {
23PlatformThreadId CurrentThreadId() {
24#if defined(WEBRTC_WIN)
25 return GetCurrentThreadId();
26#elif defined(WEBRTC_POSIX)
27 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
28 // into the kernel.
29#if defined(WEBRTC_MAC)
30 return pthread_mach_thread_np(pthread_self());
31#elif defined(WEBRTC_LINUX)
32 return syscall(__NR_gettid);
33#elif defined(WEBRTC_ANDROID)
34 return gettid();
35#else
36 // Default implementation for nacl and solaris.
37 return reinterpret_cast<pid_t>(pthread_self());
38#endif
39#endif // defined(WEBRTC_POSIX)
40}
41} // namespace
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000042
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000043ThreadCheckerImpl::ThreadCheckerImpl() : valid_thread_(CurrentThreadId()) {
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000044}
45
46ThreadCheckerImpl::~ThreadCheckerImpl() {
47}
48
49bool ThreadCheckerImpl::CalledOnValidThread() const {
50 CritScope scoped_lock(&lock_);
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000051 const PlatformThreadId current_thread = CurrentThreadId();
52 if (!valid_thread_) // Set if previously detached.
53 valid_thread_ = current_thread;
54 return valid_thread_ == current_thread;
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000055}
56
57void ThreadCheckerImpl::DetachFromThread() {
58 CritScope scoped_lock(&lock_);
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000059 valid_thread_ = 0;
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000060}
61
62} // namespace rtc