1 // Copyright 2022 gRPC authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 #ifndef GRPC_SRC_CORE_LIB_EVENT_ENGINE_FORKABLE_H 15 #define GRPC_SRC_CORE_LIB_EVENT_ENGINE_FORKABLE_H 16 17 #include <grpc/support/port_platform.h> 18 19 #include <memory> 20 #include <vector> 21 22 #include "src/core/lib/debug/trace.h" 23 24 namespace grpc_event_engine { 25 namespace experimental { 26 27 // An interface to be implemented by EventEngines that wish to have managed fork 28 // support. The child class must guarantee that those methods are thread-safe. 29 class Forkable { 30 public: 31 virtual ~Forkable() = default; 32 virtual void PrepareFork() = 0; 33 virtual void PostforkParent() = 0; 34 virtual void PostforkChild() = 0; 35 }; 36 37 // ObjectGroupForkHandler is meant to be used as a static object in each 38 // translation unit where Forkables are created and registered with the 39 // ObjectGroupForkHandler. It essentially provides storage for Forkables' 40 // instances (as a vector of weak pointers) and helper methods that are meant to 41 // be invoked inside the fork handlers (see pthread_atfork(3)). The idea is to 42 // have different Forkables (e.g. PosixEventPoller) to store their instances 43 // (e.g. a PosixEventPoller object) in a single place separated from other 44 // Forkables (a sharded approach). Forkables need to register their pthread fork 45 // handlers and manage the relative ordering themselves. This object is 46 // thread-unsafe. 47 class ObjectGroupForkHandler { 48 public: 49 // Registers a Forkable with this ObjectGroupForkHandler, the Forkable must be 50 // created as a shared pointer. 51 void RegisterForkable(std::shared_ptr<Forkable> forkable, 52 GRPC_UNUSED void (*prepare)(void), 53 GRPC_UNUSED void (*parent)(void), 54 GRPC_UNUSED void (*child)(void)); 55 56 void Prefork(); 57 void PostforkParent(); 58 void PostforkChild(); 59 60 private: 61 GRPC_UNUSED bool registered_ = false; 62 bool is_forking_ = false; 63 std::vector<std::weak_ptr<Forkable> > forkables_; 64 }; 65 66 } // namespace experimental 67 } // namespace grpc_event_engine 68 69 #endif // GRPC_SRC_CORE_LIB_EVENT_ENGINE_FORKABLE_H 70