Copyright 2014->2015
[folly.git] / folly / wangle / bootstrap / ServerBootstrap.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 #include <folly/wangle/bootstrap/ServerBootstrap.h>
17 #include <folly/wangle/concurrent/NamedThreadFactory.h>
18 #include <folly/io/async/EventBaseManager.h>
19
20 namespace folly {
21
22 void ServerWorkerPool::threadStarted(
23   folly::wangle::ThreadPoolExecutor::ThreadHandle* h) {
24   auto worker = acceptorFactory_->newAcceptor(exec_->getEventBase(h));
25   workers_.insert({h, worker});
26
27   for(auto socket : *sockets_) {
28     socket->getEventBase()->runInEventBaseThread([this, worker, socket](){
29       socket->addAcceptCallback(worker.get(), worker->getEventBase());
30     });
31   }
32 }
33
34 void ServerWorkerPool::threadStopped(
35   folly::wangle::ThreadPoolExecutor::ThreadHandle* h) {
36   auto worker = workers_.find(h);
37   CHECK(worker != workers_.end());
38
39   for (auto& socket : *sockets_) {
40     folly::Baton<> barrier;
41     socket->getEventBase()->runInEventBaseThread([&]() {
42       socket->removeAcceptCallback(worker->second.get(), nullptr);
43       barrier.post();
44     });
45     barrier.wait();
46   }
47
48   CHECK(worker->second->getEventBase() != nullptr);
49   CHECK(!worker->second->getEventBase()->isInEventBaseThread());
50   folly::Baton<> barrier;
51   worker->second->getEventBase()->runInEventBaseThread([&]() {
52       worker->second->dropAllConnections();
53       barrier.post();
54   });
55
56   barrier.wait();
57   workers_.erase(worker);
58 }
59
60 } // namespace