EventBaseManager.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/io/async/EventBaseManager.h>
  17. namespace folly {
  18. std::atomic<EventBaseManager*> globalManager(nullptr);
  19. EventBaseManager* EventBaseManager::get() {
  20. EventBaseManager* mgr = globalManager;
  21. if (mgr) {
  22. return mgr;
  23. }
  24. EventBaseManager* new_mgr = new EventBaseManager;
  25. bool exchanged = globalManager.compare_exchange_strong(mgr, new_mgr);
  26. if (!exchanged) {
  27. delete new_mgr;
  28. return mgr;
  29. } else {
  30. return new_mgr;
  31. }
  32. }
  33. /*
  34. * EventBaseManager methods
  35. */
  36. void EventBaseManager::setEventBase(EventBase* eventBase, bool takeOwnership) {
  37. EventBaseInfo* info = localStore_.get();
  38. if (info != nullptr) {
  39. throw std::runtime_error(
  40. "EventBaseManager: cannot set a new EventBase "
  41. "for this thread when one already exists");
  42. }
  43. info = new EventBaseInfo(eventBase, takeOwnership);
  44. localStore_.reset(info);
  45. this->trackEventBase(eventBase);
  46. }
  47. void EventBaseManager::clearEventBase() {
  48. EventBaseInfo* info = localStore_.get();
  49. if (info != nullptr) {
  50. this->untrackEventBase(info->eventBase);
  51. this->localStore_.reset(nullptr);
  52. }
  53. }
  54. // XXX should this really be "const"?
  55. EventBase* EventBaseManager::getEventBase() const {
  56. // have one?
  57. auto* info = localStore_.get();
  58. if (!info) {
  59. info = new EventBaseInfo();
  60. localStore_.reset(info);
  61. if (observer_) {
  62. info->eventBase->setObserver(observer_);
  63. }
  64. // start tracking the event base
  65. // XXX
  66. // note: ugly cast because this does something mutable
  67. // even though this method is defined as "const".
  68. // Simply removing the const causes trouble all over fbcode;
  69. // lots of services build a const EventBaseManager and errors
  70. // abound when we make this non-const.
  71. (const_cast<EventBaseManager*>(this))->trackEventBase(info->eventBase);
  72. }
  73. return info->eventBase;
  74. }
  75. } // namespace folly