You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.2 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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/yield_policy.h"
  11. #include "absl/base/attributes.h"
  12. #include "absl/base/config.h"
  13. #include "rtc_base/checks.h"
  14. #if !defined(ABSL_HAVE_THREAD_LOCAL) && defined(WEBRTC_POSIX)
  15. #include <pthread.h>
  16. #endif
  17. namespace rtc {
  18. namespace {
  19. #if defined(ABSL_HAVE_THREAD_LOCAL)
  20. ABSL_CONST_INIT thread_local YieldInterface* current_yield_policy = nullptr;
  21. YieldInterface* GetCurrentYieldPolicy() {
  22. return current_yield_policy;
  23. }
  24. void SetCurrentYieldPolicy(YieldInterface* ptr) {
  25. current_yield_policy = ptr;
  26. }
  27. #elif defined(WEBRTC_POSIX)
  28. // Emscripten does not support the C++11 thread_local keyword but does support
  29. // the pthread thread-local storage API.
  30. // https://github.com/emscripten-core/emscripten/issues/3502
  31. ABSL_CONST_INIT pthread_key_t g_current_yield_policy_tls = 0;
  32. void InitializeTls() {
  33. RTC_CHECK_EQ(pthread_key_create(&g_current_yield_policy_tls, nullptr), 0);
  34. }
  35. pthread_key_t GetCurrentYieldPolicyTls() {
  36. static pthread_once_t init_once = PTHREAD_ONCE_INIT;
  37. RTC_CHECK_EQ(pthread_once(&init_once, &InitializeTls), 0);
  38. return g_current_yield_policy_tls;
  39. }
  40. YieldInterface* GetCurrentYieldPolicy() {
  41. return static_cast<YieldInterface*>(
  42. pthread_getspecific(GetCurrentYieldPolicyTls()));
  43. }
  44. void SetCurrentYieldPolicy(YieldInterface* ptr) {
  45. pthread_setspecific(GetCurrentYieldPolicyTls(), ptr);
  46. }
  47. #else
  48. #error Unsupported platform
  49. #endif
  50. } // namespace
  51. ScopedYieldPolicy::ScopedYieldPolicy(YieldInterface* policy)
  52. : previous_(GetCurrentYieldPolicy()) {
  53. SetCurrentYieldPolicy(policy);
  54. }
  55. ScopedYieldPolicy::~ScopedYieldPolicy() {
  56. SetCurrentYieldPolicy(previous_);
  57. }
  58. void ScopedYieldPolicy::YieldExecution() {
  59. YieldInterface* current = GetCurrentYieldPolicy();
  60. if (current)
  61. current->YieldExecution();
  62. }
  63. } // namespace rtc