/* * ===================================================================================== * * Filename: util.h * * Description: * * Version: 1.0 * Created: 2021年03月30日 11时24分26秒 * Revision: none * Compiler: gcc * * Author: Li Chao (), * Organization: * * ===================================================================================== */ #ifndef UTIL_W8A0OA5U #define UTIL_W8A0OA5U #include "bh_util.h" #include "shm.h" #include "topic_node.h" #include #include #include #include #include #include #include #include #include #include using namespace std::chrono_literals; using namespace std::chrono; template inline void Sleep(D d, bool print = true) { if (print) { printf("sleep for %ld ms\n", std::chrono::duration_cast(d).count()); } std::this_thread::sleep_for(d); } typedef std::function FuncVV; class ScopeCall : private boost::noncopyable { FuncVV f_; public: ScopeCall(FuncVV f) : f_(f) { f_(); } ~ScopeCall() { f_(); } }; class ThreadManager { std::vector threads_; public: ~ThreadManager() { WaitAll(); } template void Launch(T &&t, P &&...p) { threads_.emplace_back(std::forward(t), std::forward(p)...); } void WaitAll() { for (auto &t : threads_) { if (t.joinable()) { t.join(); } } } }; class ProcessManager { std::vector procs_; public: ~ProcessManager() { WaitAll(); } template void Launch(T t, P... p) { auto pid = fork(); if (pid == 0) { // child t(p...); exit(0); } else if (pid != -1) { // Ok procs_.push_back(pid); } }; void WaitAll() { for (auto &pid : procs_) { int status = 0; int options = WUNTRACED | WCONTINUED; waitpid(pid, &status, options); } procs_.clear(); } }; using namespace bhome_shm; using namespace bhome_msg; struct ShmRemover { std::string name_; ShmRemover(const std::string &name) : name_(name) { SharedMemory::Remove(name_); } ~ShmRemover() { SharedMemory::Remove(name_); } }; class DemoNode : public TopicNode { std::string id_; public: DemoNode(const std::string &id, SharedMemory &shm) : TopicNode(shm), id_(id) { Init(); } void Init() { ProcInfo proc; proc.set_proc_id(id_); MsgCommonReply reply_body; if (!Register(proc, reply_body, 1000)) { printf("node %s register failed\n", id_.c_str()); } } }; bhome_shm::SharedMemory &TestShm(); #endif // end of include guard: UTIL_W8A0OA5U