blob: 0b419d9505355e700901cb71711c93bc33538cea [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.orgd43bdf52015-02-03 16:29:57 +000022
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000023PlatformThreadId 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.
tommi@webrtc.orgd43bdf52015-02-03 16:29:57 +000029#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000030 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}
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000041
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000042ThreadCheckerImpl::ThreadCheckerImpl() : valid_thread_(CurrentThreadId()) {
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000043}
44
45ThreadCheckerImpl::~ThreadCheckerImpl() {
46}
47
48bool ThreadCheckerImpl::CalledOnValidThread() const {
49 CritScope scoped_lock(&lock_);
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000050 const PlatformThreadId current_thread = CurrentThreadId();
51 if (!valid_thread_) // Set if previously detached.
52 valid_thread_ = current_thread;
53 return valid_thread_ == current_thread;
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000054}
55
56void ThreadCheckerImpl::DetachFromThread() {
57 CritScope scoped_lock(&lock_);
tommi@webrtc.org04cd4662015-01-26 15:27:29 +000058 valid_thread_ = 0;
henrik.lundin@webrtc.org1e3c5c22014-06-16 11:34:44 +000059}
60
61} // namespace rtc