Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  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.  
  12. #include "absl/base/attributes.h"
  13.  
  14. #include <thread>
  15. #include <mutex>
  16. #include <map>
  17. #include <sys/types.h>
  18.  
  19. template<typename T>
  20. class ThreadLocalValue {
  21. public:
  22. T get() {
  23. std::thread::id thread_id = std::this_thread::get_id();
  24. m.lock();
  25. T result = tr[thread_id];
  26. m.unlock();
  27. return result;
  28. }
  29. void set(T t) {
  30. std::thread::id thread_id = std::this_thread::get_id();
  31. m.lock();
  32. tr[thread_id] = t;
  33. m.unlock();
  34. }
  35. private:
  36. std::map<std::thread::id, T> tr;
  37. std::mutex m;
  38. };
  39.  
  40.  
  41. namespace rtc {
  42.  
  43. ThreadLocalValue<YieldInterface *>& getInstance() {
  44. /* Have a static local variable representing the unique instance. Since
  45. * it's static, there is only one instance of this variable. It's also only
  46. * initialized when getInstance is called.
  47. */
  48. static ThreadLocalValue<YieldInterface *> *theInstance = new ThreadLocalValue<YieldInterface*>();
  49. return *theInstance;
  50. }
  51.  
  52. ScopedYieldPolicy::ScopedYieldPolicy(YieldInterface* policy)
  53. : previous_(getInstance().get()) {
  54. getInstance().set(policy);
  55. }
  56.  
  57. ScopedYieldPolicy::~ScopedYieldPolicy() {
  58. getInstance().set(previous_);
  59. }
  60.  
  61. void ScopedYieldPolicy::YieldExecution() {
  62. YieldInterface *inter = getInstance().get();
  63. if (inter) {
  64. inter->YieldExecution();
  65. }
  66. }
  67. } // namespace rtc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement