Add a default timeout parameter to HHWheelTimer.
[folly.git] / folly / io / async / ScopedEventBaseThread.cpp
1 /*
2  * Copyright 2015 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
17 #include <folly/io/async/ScopedEventBaseThread.h>
18
19 #include <thread>
20 #include <folly/Memory.h>
21
22 using namespace std;
23
24 namespace folly {
25
26 static void run(EventBaseManager* ebm, EventBase* eb) {
27   if (ebm) {
28     ebm->setEventBase(eb, false);
29   }
30   CHECK_NOTNULL(eb)->loopForever();
31   if (ebm) {
32     ebm->clearEventBase();
33   }
34 }
35
36 ScopedEventBaseThread::ScopedEventBaseThread(
37     bool autostart,
38     EventBaseManager* ebm) :
39   ebm_(ebm) {
40   if (autostart) {
41     start();
42   }
43 }
44
45 ScopedEventBaseThread::ScopedEventBaseThread(
46     EventBaseManager* ebm) :
47   ScopedEventBaseThread(true, ebm) {}
48
49 ScopedEventBaseThread::~ScopedEventBaseThread() {
50   stop();
51 }
52
53 ScopedEventBaseThread::ScopedEventBaseThread(
54     ScopedEventBaseThread&& other) noexcept = default;
55
56 ScopedEventBaseThread& ScopedEventBaseThread::operator=(
57     ScopedEventBaseThread&& other) noexcept = default;
58
59 void ScopedEventBaseThread::start() {
60   if (running()) {
61     return;
62   }
63   eventBase_ = make_unique<EventBase>();
64   thread_ = make_unique<thread>(run, ebm_, eventBase_.get());
65   eventBase_->waitUntilRunning();
66 }
67
68 void ScopedEventBaseThread::stop() {
69   if (!running()) {
70     return;
71   }
72   eventBase_->terminateLoopSoon();
73   thread_->join();
74   eventBase_ = nullptr;
75   thread_ = nullptr;
76 }
77
78 bool ScopedEventBaseThread::running() {
79   CHECK(bool(eventBase_) == bool(thread_));
80   return eventBase_ && thread_;
81 }
82
83 }