task_queue_base.cc (1919B)
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 "api/task_queue/task_queue_base.h" 11 12 #include "absl/base/attributes.h" 13 #include "absl/base/config.h" 14 15 #if defined(ABSL_HAVE_THREAD_LOCAL) 16 17 namespace webrtc { 18 namespace { 19 20 ABSL_CONST_INIT thread_local TaskQueueBase* current = nullptr; 21 22 } // namespace 23 24 TaskQueueBase* TaskQueueBase::Current() { 25 return current; 26 } 27 28 TaskQueueBase::CurrentTaskQueueSetter::CurrentTaskQueueSetter( 29 TaskQueueBase* task_queue) 30 : previous_(current) { 31 current = task_queue; 32 } 33 34 TaskQueueBase::CurrentTaskQueueSetter::~CurrentTaskQueueSetter() { 35 current = previous_; 36 } 37 } // namespace webrtc 38 39 #elif defined(WEBRTC_POSIX) 40 41 #include <pthread.h> 42 43 namespace webrtc { 44 namespace { 45 46 ABSL_CONST_INIT pthread_key_t g_queue_ptr_tls = 0; 47 48 void InitializeTls() { 49 RTC_CHECK(pthread_key_create(&g_queue_ptr_tls, nullptr) == 0); 50 } 51 52 pthread_key_t GetQueuePtrTls() { 53 static pthread_once_t init_once = PTHREAD_ONCE_INIT; 54 RTC_CHECK(pthread_once(&init_once, &InitializeTls) == 0); 55 return g_queue_ptr_tls; 56 } 57 58 } // namespace 59 60 TaskQueueBase* TaskQueueBase::Current() { 61 return static_cast<TaskQueueBase*>(pthread_getspecific(GetQueuePtrTls())); 62 } 63 64 TaskQueueBase::CurrentTaskQueueSetter::CurrentTaskQueueSetter( 65 TaskQueueBase* task_queue) 66 : previous_(TaskQueueBase::Current()) { 67 pthread_setspecific(GetQueuePtrTls(), task_queue); 68 } 69 70 TaskQueueBase::CurrentTaskQueueSetter::~CurrentTaskQueueSetter() { 71 pthread_setspecific(GetQueuePtrTls(), previous_); 72 } 73 74 } // namespace webrtc 75 76 #else 77 #error Unsupported platform 78 #endif