Branch data Line data Source code
1 : : /*
2 : : * Copyright 2025 Jinwoo Sung
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 : : #pragma once
18 : :
19 : : #include <boost/asio/executor_work_guard.hpp>
20 : : #include <boost/asio/io_context.hpp>
21 : : #include <memory>
22 : :
23 : : #include "wirestead/base/visibility.hpp"
24 : :
25 : : namespace wirestead {
26 : : namespace concurrency {
27 : :
28 : : /**
29 : : * Global io_context manager.
30 : : *
31 : : * Every transport (TcpClient/TcpServer/UdsClient/UdsServer/UdpChannel/Serial)
32 : : * owns a dedicated io_context + thread by default (#440). This singleton
33 : : * backs the opt-in shared_context() builder/wrapper setter on TcpServer and
34 : : * Serial only, for callers who deliberately want many instances in one
35 : : * process to share a single thread (trading per-instance parallelism for
36 : : * reduced thread/memory overhead) instead of each running independently.
37 : : */
38 : : class WIRESTEAD_API IoContextManager {
39 : : public:
40 : : using IoContext = boost::asio::io_context;
41 : : using WorkGuard = boost::asio::executor_work_guard<IoContext::executor_type>;
42 : :
43 : : static IoContextManager& instance();
44 : :
45 : : IoContextManager();
46 : : explicit IoContextManager(std::shared_ptr<IoContext> external_context);
47 : : explicit IoContextManager(IoContext& external_context);
48 : : ~IoContextManager();
49 : :
50 : : // Move semantics
51 : : IoContextManager(IoContextManager&&) noexcept;
52 : : IoContextManager& operator=(IoContextManager&&) noexcept;
53 : :
54 : : // Non-copyable
55 : : IoContextManager(const IoContextManager&) = delete;
56 : : IoContextManager& operator=(const IoContextManager&) = delete;
57 : :
58 : : IoContext& get_context();
59 : : void start();
60 : : void stop();
61 : : bool is_running() const;
62 : : std::unique_ptr<IoContext> create_independent_context();
63 : :
64 : : private:
65 : : struct Impl;
66 : 400 : const Impl* get_impl() const { return impl_.get(); }
67 : : Impl* get_impl() { return impl_.get(); }
68 : : std::unique_ptr<Impl> impl_;
69 : : };
70 : :
71 : : } // namespace concurrency
72 : :
73 : : } // namespace wirestead
|