688faf5e82f4a7265767b074672696e42b082c82
[folly.git] / folly / io / async / VirtualEventBase.cpp
1 /*
2  * Copyright 2017 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/VirtualEventBase.h>
17
18 namespace folly {
19
20 VirtualEventBase::VirtualEventBase(EventBase& evb) : evb_(evb) {
21   evbLoopKeepAlive_ = evb_.getKeepAliveToken();
22   loopKeepAlive_ = getKeepAliveToken();
23 }
24
25 std::future<void> VirtualEventBase::destroy() {
26   CHECK(evb_.runInEventBaseThread([this] { loopKeepAlive_.reset(); }));
27
28   return std::move(destroyFuture_);
29 }
30
31 void VirtualEventBase::destroyImpl() {
32   // Make sure we release EventBase KeepAlive token even if exception occurs
33   auto evbLoopKeepAlive = std::move(evbLoopKeepAlive_);
34   try {
35     clearCobTimeouts();
36
37     onDestructionCallbacks_.withWLock([&](LoopCallbackList& callbacks) {
38       while (!callbacks.empty()) {
39         auto& callback = callbacks.front();
40         callbacks.pop_front();
41         callback.runLoopCallback();
42       }
43     });
44
45     destroyPromise_.set_value();
46   } catch (...) {
47     destroyPromise_.set_exception(std::current_exception());
48   }
49 }
50
51 VirtualEventBase::~VirtualEventBase() {
52   if (!destroyFuture_.valid()) {
53     return;
54   }
55   CHECK(!evb_.inRunningEventBaseThread());
56   destroy().get();
57 }
58
59 void VirtualEventBase::runOnDestruction(EventBase::LoopCallback* callback) {
60   onDestructionCallbacks_.withWLock([&](LoopCallbackList& callbacks) {
61     callback->cancelLoopCallback();
62     callbacks.push_back(*callback);
63   });
64 }
65 }