Sebastian Jansson | df5e4e0 | 2019-03-29 10:34:45 +0100 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019 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 | #include "rtc_base/synchronization/sequence_checker.h" |
| 11 | |
| 12 | #if defined(WEBRTC_MAC) |
| 13 | #include <dispatch/dispatch.h> |
| 14 | #endif |
| 15 | |
| 16 | namespace webrtc { |
| 17 | namespace { |
| 18 | // On Mac, returns the label of the current dispatch queue; elsewhere, return |
| 19 | // null. |
| 20 | const void* GetSystemQueueRef() { |
| 21 | #if defined(WEBRTC_MAC) |
| 22 | return dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL); |
| 23 | #else |
| 24 | return nullptr; |
| 25 | #endif |
| 26 | } |
| 27 | } // namespace |
| 28 | |
| 29 | SequenceCheckerImpl::SequenceCheckerImpl() |
| 30 | : attached_(true), |
| 31 | valid_thread_(rtc::CurrentThreadRef()), |
| 32 | valid_queue_(TaskQueueBase::Current()), |
| 33 | valid_system_queue_(GetSystemQueueRef()) {} |
| 34 | |
| 35 | SequenceCheckerImpl::~SequenceCheckerImpl() = default; |
| 36 | |
| 37 | bool SequenceCheckerImpl::IsCurrent() const { |
| 38 | const TaskQueueBase* const current_queue = TaskQueueBase::Current(); |
| 39 | const rtc::PlatformThreadRef current_thread = rtc::CurrentThreadRef(); |
| 40 | const void* const current_system_queue = GetSystemQueueRef(); |
| 41 | rtc::CritScope scoped_lock(&lock_); |
| 42 | if (!attached_) { // Previously detached. |
| 43 | attached_ = true; |
| 44 | valid_thread_ = current_thread; |
| 45 | valid_queue_ = current_queue; |
| 46 | valid_system_queue_ = current_system_queue; |
| 47 | return true; |
| 48 | } |
| 49 | if (valid_queue_ || current_queue) { |
| 50 | return valid_queue_ == current_queue; |
| 51 | } |
| 52 | if (valid_system_queue_ && valid_system_queue_ == current_system_queue) { |
| 53 | return true; |
| 54 | } |
| 55 | return rtc::IsThreadRefEqual(valid_thread_, current_thread); |
| 56 | } |
| 57 | |
| 58 | void SequenceCheckerImpl::Detach() { |
| 59 | rtc::CritScope scoped_lock(&lock_); |
| 60 | attached_ = false; |
| 61 | // We don't need to touch the other members here, they will be |
| 62 | // reset on the next call to IsCurrent(). |
| 63 | } |
| 64 | |
| 65 | } // namespace webrtc |