1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
//
3  
//
4  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
4  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
//
6  
//
7  
// Official repository: https://github.com/cppalliance/capy
7  
// Official repository: https://github.com/cppalliance/capy
8  
//
8  
//
9  

9  

10  
#ifndef BOOST_CAPY_EXECUTION_CONTEXT_HPP
10  
#ifndef BOOST_CAPY_EXECUTION_CONTEXT_HPP
11  
#define BOOST_CAPY_EXECUTION_CONTEXT_HPP
11  
#define BOOST_CAPY_EXECUTION_CONTEXT_HPP
12  

12  

13  
#include <boost/capy/detail/config.hpp>
13  
#include <boost/capy/detail/config.hpp>
14 -
#include <boost/capy/detail/service_slot.hpp>
 
15  
#include <boost/capy/detail/frame_memory_resource.hpp>
14  
#include <boost/capy/detail/frame_memory_resource.hpp>
16  
#include <boost/capy/detail/type_id.hpp>
15  
#include <boost/capy/detail/type_id.hpp>
17 -
#include <atomic>
 
18  
#include <boost/capy/concept/executor.hpp>
16  
#include <boost/capy/concept/executor.hpp>
19  
#include <concepts>
17  
#include <concepts>
20  
#include <memory>
18  
#include <memory>
21  
#include <memory_resource>
19  
#include <memory_resource>
22  
#include <mutex>
20  
#include <mutex>
23  
#include <tuple>
21  
#include <tuple>
24  
#include <type_traits>
22  
#include <type_traits>
25  
#include <utility>
23  
#include <utility>
26  

24  

27  
namespace boost {
25  
namespace boost {
28  
namespace capy {
26  
namespace capy {
29  

27  

30  
/** Base class for I/O object containers providing service management.
28  
/** Base class for I/O object containers providing service management.
31  

29  

32  
    An execution context represents a place where function objects are
30  
    An execution context represents a place where function objects are
33  
    executed. It provides a service registry where polymorphic services
31  
    executed. It provides a service registry where polymorphic services
34  
    can be stored and retrieved by type. Each service type may be stored
32  
    can be stored and retrieved by type. Each service type may be stored
35  
    at most once. Services may specify a nested `key_type` to enable
33  
    at most once. Services may specify a nested `key_type` to enable
36  
    lookup by a base class type.
34  
    lookup by a base class type.
37  

35  

38  
    Derived classes such as `io_context` extend this to provide
36  
    Derived classes such as `io_context` extend this to provide
39  
    execution facilities like event loops and thread pools. Derived
37  
    execution facilities like event loops and thread pools. Derived
40  
    class destructors must call `shutdown()` and `destroy()` to ensure
38  
    class destructors must call `shutdown()` and `destroy()` to ensure
41  
    proper service cleanup before member destruction.
39  
    proper service cleanup before member destruction.
42  

40  

43  
    @par Service Lifecycle
41  
    @par Service Lifecycle
44  
    Services are created on first use via `use_service()` or explicitly
42  
    Services are created on first use via `use_service()` or explicitly
45  
    via `make_service()`. During destruction, `shutdown()` is called on
43  
    via `make_service()`. During destruction, `shutdown()` is called on
46  
    each service in reverse order of creation, then `destroy()` deletes
44  
    each service in reverse order of creation, then `destroy()` deletes
47  
    them. Both functions are idempotent.
45  
    them. Both functions are idempotent.
48  

46  

49  
    @par Thread Safety
47  
    @par Thread Safety
50  
    Service registration and lookup functions are thread-safe.
48  
    Service registration and lookup functions are thread-safe.
51  
    The `shutdown()` and `destroy()` functions are not thread-safe
49  
    The `shutdown()` and `destroy()` functions are not thread-safe
52  
    and must only be called during destruction.
50  
    and must only be called during destruction.
53  

51  

54  
    @par Example
52  
    @par Example
55  
    @code
53  
    @code
56  
    struct file_service : execution_context::service
54  
    struct file_service : execution_context::service
57  
    {
55  
    {
58  
    protected:
56  
    protected:
59  
        void shutdown() override {}
57  
        void shutdown() override {}
60  
    };
58  
    };
61  

59  

62  
    struct posix_file_service : file_service
60  
    struct posix_file_service : file_service
63  
    {
61  
    {
64  
        using key_type = file_service;
62  
        using key_type = file_service;
65  

63  

66  
        explicit posix_file_service(execution_context&) {}
64  
        explicit posix_file_service(execution_context&) {}
67  
    };
65  
    };
68  

66  

69  
    class io_context : public execution_context
67  
    class io_context : public execution_context
70  
    {
68  
    {
71  
    public:
69  
    public:
72  
        ~io_context()
70  
        ~io_context()
73  
        {
71  
        {
74  
            shutdown();
72  
            shutdown();
75  
            destroy();
73  
            destroy();
76  
        }
74  
        }
77  
    };
75  
    };
78  

76  

79  
    io_context ctx;
77  
    io_context ctx;
80  
    ctx.make_service<posix_file_service>();
78  
    ctx.make_service<posix_file_service>();
81  
    ctx.find_service<file_service>();       // returns posix_file_service*
79  
    ctx.find_service<file_service>();       // returns posix_file_service*
82  
    ctx.find_service<posix_file_service>(); // also works
80  
    ctx.find_service<posix_file_service>(); // also works
83  
    @endcode
81  
    @endcode
84  

82  

85  
    @see service, is_execution_context
83  
    @see service, is_execution_context
86  
*/
84  
*/
87  
class BOOST_CAPY_DECL
85  
class BOOST_CAPY_DECL
88  
    execution_context
86  
    execution_context
89  
{
87  
{
90  
    detail::type_info const* ti_ = nullptr;
88  
    detail::type_info const* ti_ = nullptr;
91  

89  

92  
    template<class T, class = void>
90  
    template<class T, class = void>
93  
    struct get_key : std::false_type
91  
    struct get_key : std::false_type
94  
    {};
92  
    {};
95  

93  

96  
    template<class T>
94  
    template<class T>
97  
    struct get_key<T, std::void_t<typename T::key_type>> : std::true_type
95  
    struct get_key<T, std::void_t<typename T::key_type>> : std::true_type
98  
    {
96  
    {
99  
        using type = typename T::key_type;
97  
        using type = typename T::key_type;
100  
    };
98  
    };
101  
protected:
99  
protected:
102  
    template< typename Derived >
100  
    template< typename Derived >
103  
    explicit execution_context( Derived* ) noexcept;
101  
    explicit execution_context( Derived* ) noexcept;
104  

102  

105  
public:
103  
public:
106  
    //------------------------------------------------
104  
    //------------------------------------------------
107  

105  

108  
    /** Abstract base class for services owned by an execution context.
106  
    /** Abstract base class for services owned by an execution context.
109  

107  

110  
        Services provide extensible functionality to an execution context.
108  
        Services provide extensible functionality to an execution context.
111  
        Each service type can be registered at most once. Services are
109  
        Each service type can be registered at most once. Services are
112  
        created via `use_service()` or `make_service()` and are owned by
110  
        created via `use_service()` or `make_service()` and are owned by
113  
        the execution context for their lifetime.
111  
        the execution context for their lifetime.
114  

112  

115  
        Derived classes must implement the pure virtual `shutdown()` member
113  
        Derived classes must implement the pure virtual `shutdown()` member
116  
        function, which is called when the owning execution context is
114  
        function, which is called when the owning execution context is
117  
        being destroyed. The `shutdown()` function should release resources
115  
        being destroyed. The `shutdown()` function should release resources
118  
        and cancel outstanding operations without blocking.
116  
        and cancel outstanding operations without blocking.
119  

117  

120  
        @par Deriving from service
118  
        @par Deriving from service
121  
        @li Implement `shutdown()` to perform cleanup.
119  
        @li Implement `shutdown()` to perform cleanup.
122  
        @li Accept `execution_context&` as the first constructor parameter.
120  
        @li Accept `execution_context&` as the first constructor parameter.
123  
        @li Optionally define `key_type` to enable base-class lookup.
121  
        @li Optionally define `key_type` to enable base-class lookup.
124  

122  

125  
        @par Example
123  
        @par Example
126  
        @code
124  
        @code
127  
        struct my_service : execution_context::service
125  
        struct my_service : execution_context::service
128  
        {
126  
        {
129  
            explicit my_service(execution_context&) {}
127  
            explicit my_service(execution_context&) {}
130  

128  

131  
        protected:
129  
        protected:
132  
            void shutdown() override
130  
            void shutdown() override
133  
            {
131  
            {
134  
                // Cancel pending operations, release resources
132  
                // Cancel pending operations, release resources
135  
            }
133  
            }
136  
        };
134  
        };
137  
        @endcode
135  
        @endcode
138  

136  

139  
        @see execution_context
137  
        @see execution_context
140  
    */
138  
    */
141  
    class BOOST_CAPY_DECL
139  
    class BOOST_CAPY_DECL
142  
        service
140  
        service
143  
    {
141  
    {
144  
    public:
142  
    public:
145  
        virtual ~service() = default;
143  
        virtual ~service() = default;
146  

144  

147  
    protected:
145  
    protected:
148  
        service() = default;
146  
        service() = default;
149  

147  

150  
        /** Called when the owning execution context shuts down.
148  
        /** Called when the owning execution context shuts down.
151  

149  

152  
            Implementations should release resources and cancel any
150  
            Implementations should release resources and cancel any
153  
            outstanding asynchronous operations. This function must
151  
            outstanding asynchronous operations. This function must
154  
            not block and must not throw exceptions. Services are
152  
            not block and must not throw exceptions. Services are
155  
            shut down in reverse order of creation.
153  
            shut down in reverse order of creation.
156  

154  

157  
            @par Exception Safety
155  
            @par Exception Safety
158  
            No-throw guarantee.
156  
            No-throw guarantee.
159  
        */
157  
        */
160  
        virtual void shutdown() = 0;
158  
        virtual void shutdown() = 0;
161  

159  

162  
    private:
160  
    private:
163  
        friend class execution_context;
161  
        friend class execution_context;
164  

162  

165  
        service* next_ = nullptr;
163  
        service* next_ = nullptr;
166  

164  

167  
// warning C4251: 'std::type_index' needs to have dll-interface
165  
// warning C4251: 'std::type_index' needs to have dll-interface
168  
        BOOST_CAPY_MSVC_WARNING_PUSH
166  
        BOOST_CAPY_MSVC_WARNING_PUSH
169  
        BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
167  
        BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
170  
        detail::type_index t0_{detail::type_id<void>()};
168  
        detail::type_index t0_{detail::type_id<void>()};
171  
        detail::type_index t1_{detail::type_id<void>()};
169  
        detail::type_index t1_{detail::type_id<void>()};
172  
        BOOST_CAPY_MSVC_WARNING_POP
170  
        BOOST_CAPY_MSVC_WARNING_POP
173  
    };
171  
    };
174  

172  

175  
    //------------------------------------------------
173  
    //------------------------------------------------
176  

174  

177  
    execution_context(execution_context const&) = delete;
175  
    execution_context(execution_context const&) = delete;
178  

176  

179  
    execution_context& operator=(execution_context const&) = delete;
177  
    execution_context& operator=(execution_context const&) = delete;
180  

178  

181  
    /** Destructor.
179  
    /** Destructor.
182  

180  

183  
        Calls `shutdown()` then `destroy()` to clean up all services.
181  
        Calls `shutdown()` then `destroy()` to clean up all services.
184  

182  

185  
        @par Effects
183  
        @par Effects
186  
        All services are shut down and deleted in reverse order
184  
        All services are shut down and deleted in reverse order
187  
        of creation.
185  
        of creation.
188  

186  

189  
        @par Exception Safety
187  
        @par Exception Safety
190  
        No-throw guarantee.
188  
        No-throw guarantee.
191  
    */
189  
    */
192  
    ~execution_context();
190  
    ~execution_context();
193  

191  

194  
    /** Construct a default instance.
192  
    /** Construct a default instance.
195  

193  

196  
        @par Exception Safety
194  
        @par Exception Safety
197  
        Strong guarantee.
195  
        Strong guarantee.
198  
    */
196  
    */
199  
    execution_context();
197  
    execution_context();
200  

198  

201  
    /** Return true if a service of type T exists.
199  
    /** Return true if a service of type T exists.
202  

200  

203  
        @par Thread Safety
201  
        @par Thread Safety
204  
        Thread-safe.
202  
        Thread-safe.
205  

203  

206  
        @tparam T The type of service to check.
204  
        @tparam T The type of service to check.
207  

205  

208  
        @return `true` if the service exists.
206  
        @return `true` if the service exists.
209  
    */
207  
    */
210  
    template<class T>
208  
    template<class T>
211  
    bool has_service() const noexcept
209  
    bool has_service() const noexcept
212  
    {
210  
    {
213  
        return find_service<T>() != nullptr;
211  
        return find_service<T>() != nullptr;
214  
    }
212  
    }
215  

213  

216  
    /** Return a pointer to the service of type T, or nullptr.
214  
    /** Return a pointer to the service of type T, or nullptr.
217  

215  

218  
        @par Thread Safety
216  
        @par Thread Safety
219  
        Thread-safe.
217  
        Thread-safe.
220  

218  

221  
        @tparam T The type of service to find.
219  
        @tparam T The type of service to find.
222  

220  

223  
        @return A pointer to the service, or `nullptr` if not present.
221  
        @return A pointer to the service, or `nullptr` if not present.
224  
    */
222  
    */
225  
    template<class T>
223  
    template<class T>
226  
    T* find_service() const noexcept
224  
    T* find_service() const noexcept
227 -
        auto id = detail::service_slot<T>();
 
228 -
        if(id < max_service_slots)
 
229 -
        {
 
230 -
            auto* p = slots_[id].load(
 
231 -
                std::memory_order_acquire);
 
232 -
            if(p)
 
233 -
                return static_cast<T*>(p);
 
234 -
        }
 
235  
    {
225  
    {
236  
        std::lock_guard<std::mutex> lock(mutex_);
226  
        std::lock_guard<std::mutex> lock(mutex_);
237  
        return static_cast<T*>(find_impl(detail::type_id<T>()));
227  
        return static_cast<T*>(find_impl(detail::type_id<T>()));
238  
    }
228  
    }
239  

229  

240  
    /** Return a reference to the service of type T, creating it if needed.
230  
    /** Return a reference to the service of type T, creating it if needed.
241  

231  

242  
        If no service of type T exists, one is created by calling
232  
        If no service of type T exists, one is created by calling
243  
        `T(execution_context&)`. If T has a nested `key_type`, the
233  
        `T(execution_context&)`. If T has a nested `key_type`, the
244  
        service is also indexed under that type.
234  
        service is also indexed under that type.
245  

235  

246  
        @par Constraints
236  
        @par Constraints
247  
        @li `T` must derive from `service`.
237  
        @li `T` must derive from `service`.
248  
        @li `T` must be constructible from `execution_context&`.
238  
        @li `T` must be constructible from `execution_context&`.
249  

239  

250  
        @par Exception Safety
240  
        @par Exception Safety
251  
        Strong guarantee. If service creation throws, the container
241  
        Strong guarantee. If service creation throws, the container
252  
        is unchanged.
242  
        is unchanged.
253  

243  

254  
        @par Thread Safety
244  
        @par Thread Safety
255  
        Thread-safe.
245  
        Thread-safe.
256  

246  

257  
        @tparam T The type of service to retrieve or create.
247  
        @tparam T The type of service to retrieve or create.
258  

248  

259  
        @return A reference to the service.
249  
        @return A reference to the service.
260  
    */
250  
    */
261  
    template<class T>
251  
    template<class T>
262  
    T& use_service()
252  
    T& use_service()
263  
    {
253  
    {
264  
        static_assert(std::is_base_of<service, T>::value,
254  
        static_assert(std::is_base_of<service, T>::value,
265  
            "T must derive from service");
255  
            "T must derive from service");
266  
        static_assert(std::is_constructible<T, execution_context&>::value,
256  
        static_assert(std::is_constructible<T, execution_context&>::value,
267 -
        if constexpr(get_key<T>::value)
 
268 -
        {
 
269 -
            static_assert(
 
270 -
                std::is_convertible<T&, typename get_key<T>::type&>::value,
 
271 -
                "T& must be convertible to key_type&");
 
272 -
        }
 
273 -

 
274 -
        // Fast path: O(1) slot lookup
 
275 -
        {
 
276 -
            auto id = detail::service_slot<T>();
 
277 -
            if(id < max_service_slots)
 
278 -
            {
 
279 -
                auto* p = slots_[id].load(
 
280 -
                    std::memory_order_acquire);
 
281 -
                if(p)
 
282 -
                    return static_cast<T&>(*p);
 
283 -
            }
 
284 -
        }
 
285  
            "T must be constructible from execution_context&");
257  
            "T must be constructible from execution_context&");
286  

258  

287  
        struct impl : factory
259  
        struct impl : factory
288  
        {
260  
        {
289  
            impl()
261  
            impl()
290  
                : factory(
262  
                : factory(
291  
                    detail::type_id<T>(),
263  
                    detail::type_id<T>(),
292  
                    get_key<T>::value
264  
                    get_key<T>::value
293  
                        ? detail::type_id<typename get_key<T>::type>()
265  
                        ? detail::type_id<typename get_key<T>::type>()
294 -
                        : detail::type_id<T>(),
266 +
                        : detail::type_id<T>())
295 -
                    detail::service_slot<T>(),
 
296 -
                    get_key<T>::value
 
297 -
                        ? detail::service_slot<typename get_key<T>::type>()
 
298 -
                        : detail::service_slot<T>())
 
299  
            {
267  
            {
300  
            }
268  
            }
301  

269  

302  
            service* create(execution_context& ctx) override
270  
            service* create(execution_context& ctx) override
303  
            {
271  
            {
304  
                return new T(ctx);
272  
                return new T(ctx);
305  
            }
273  
            }
306  
        };
274  
        };
307  

275  

308  
        impl f;
276  
        impl f;
309  
        return static_cast<T&>(use_service_impl(f));
277  
        return static_cast<T&>(use_service_impl(f));
310  
    }
278  
    }
311  

279  

312  
    /** Construct and add a service.
280  
    /** Construct and add a service.
313  

281  

314  
        A new service of type T is constructed using the provided
282  
        A new service of type T is constructed using the provided
315  
        arguments and added to the container. If T has a nested
283  
        arguments and added to the container. If T has a nested
316  
        `key_type`, the service is also indexed under that type.
284  
        `key_type`, the service is also indexed under that type.
317  

285  

318  
        @par Constraints
286  
        @par Constraints
319  
        @li `T` must derive from `service`.
287  
        @li `T` must derive from `service`.
320  
        @li `T` must be constructible from `execution_context&, Args...`.
288  
        @li `T` must be constructible from `execution_context&, Args...`.
321  
        @li If `T::key_type` exists, `T&` must be convertible to `key_type&`.
289  
        @li If `T::key_type` exists, `T&` must be convertible to `key_type&`.
322  

290  

323  
        @par Exception Safety
291  
        @par Exception Safety
324  
        Strong guarantee. If service creation throws, the container
292  
        Strong guarantee. If service creation throws, the container
325  
        is unchanged.
293  
        is unchanged.
326  

294  

327  
        @par Thread Safety
295  
        @par Thread Safety
328  
        Thread-safe.
296  
        Thread-safe.
329  

297  

330  
        @throws std::invalid_argument if a service of the same type
298  
        @throws std::invalid_argument if a service of the same type
331  
            or `key_type` already exists.
299  
            or `key_type` already exists.
332  

300  

333  
        @tparam T The type of service to create.
301  
        @tparam T The type of service to create.
334  

302  

335  
        @param args Arguments forwarded to the constructor of T.
303  
        @param args Arguments forwarded to the constructor of T.
336  

304  

337  
        @return A reference to the created service.
305  
        @return A reference to the created service.
338  
    */
306  
    */
339  
    template<class T, class... Args>
307  
    template<class T, class... Args>
340  
    T& make_service(Args&&... args)
308  
    T& make_service(Args&&... args)
341  
    {
309  
    {
342  
        static_assert(std::is_base_of<service, T>::value,
310  
        static_assert(std::is_base_of<service, T>::value,
343  
            "T must derive from service");
311  
            "T must derive from service");
344  
        if constexpr(get_key<T>::value)
312  
        if constexpr(get_key<T>::value)
345  
        {
313  
        {
346  
            static_assert(
314  
            static_assert(
347  
                std::is_convertible<T&, typename get_key<T>::type&>::value,
315  
                std::is_convertible<T&, typename get_key<T>::type&>::value,
348  
                "T& must be convertible to key_type&");
316  
                "T& must be convertible to key_type&");
349  
        }
317  
        }
350  

318  

351  
        struct impl : factory
319  
        struct impl : factory
352  
        {
320  
        {
353  
            std::tuple<Args&&...> args_;
321  
            std::tuple<Args&&...> args_;
354  

322  

355  
            explicit impl(Args&&... a)
323  
            explicit impl(Args&&... a)
356  
                : factory(
324  
                : factory(
357  
                    detail::type_id<T>(),
325  
                    detail::type_id<T>(),
358  
                    get_key<T>::value
326  
                    get_key<T>::value
359  
                        ? detail::type_id<typename get_key<T>::type>()
327  
                        ? detail::type_id<typename get_key<T>::type>()
360 -
                        : detail::type_id<T>(),
328 +
                        : detail::type_id<T>())
361 -
                    detail::service_slot<T>(),
 
362 -
                    get_key<T>::value
 
363 -
                        ? detail::service_slot<typename get_key<T>::type>()
 
364 -
                        : detail::service_slot<T>())
 
365  
                , args_(std::forward<Args>(a)...)
329  
                , args_(std::forward<Args>(a)...)
366  
            {
330  
            {
367  
            }
331  
            }
368  

332  

369  
            service* create(execution_context& ctx) override
333  
            service* create(execution_context& ctx) override
370  
            {
334  
            {
371  
                return std::apply([&ctx](auto&&... a) {
335  
                return std::apply([&ctx](auto&&... a) {
372  
                    return new T(ctx, std::forward<decltype(a)>(a)...);
336  
                    return new T(ctx, std::forward<decltype(a)>(a)...);
373  
                }, std::move(args_));
337  
                }, std::move(args_));
374  
            }
338  
            }
375  
        };
339  
        };
376  

340  

377  
        impl f(std::forward<Args>(args)...);
341  
        impl f(std::forward<Args>(args)...);
378  
        return static_cast<T&>(make_service_impl(f));
342  
        return static_cast<T&>(make_service_impl(f));
379  
    }
343  
    }
380  

344  

381  
    //------------------------------------------------
345  
    //------------------------------------------------
382  

346  

383  
    /** Return the memory resource used for coroutine frame allocation.
347  
    /** Return the memory resource used for coroutine frame allocation.
384  

348  

385  
        The returned pointer is valid for the lifetime of this context.
349  
        The returned pointer is valid for the lifetime of this context.
386  
        By default, this returns a pointer to the recycling memory
350  
        By default, this returns a pointer to the recycling memory
387  
        resource which pools frame allocations for reuse.
351  
        resource which pools frame allocations for reuse.
388  

352  

389  
        @return Pointer to the frame allocator.
353  
        @return Pointer to the frame allocator.
390  

354  

391  
        @see set_frame_allocator
355  
        @see set_frame_allocator
392  
    */
356  
    */
393  
    std::pmr::memory_resource*
357  
    std::pmr::memory_resource*
394  
    get_frame_allocator() const noexcept
358  
    get_frame_allocator() const noexcept
395  
    {
359  
    {
396  
        return frame_alloc_;
360  
        return frame_alloc_;
397  
    }
361  
    }
398  

362  

399  
    /** Set the memory resource used for coroutine frame allocation.
363  
    /** Set the memory resource used for coroutine frame allocation.
400  

364  

401  
        The caller is responsible for ensuring the memory resource
365  
        The caller is responsible for ensuring the memory resource
402  
        remains valid for the lifetime of all coroutines launched
366  
        remains valid for the lifetime of all coroutines launched
403  
        using this context's executor.
367  
        using this context's executor.
404  

368  

405  
        @par Thread Safety
369  
        @par Thread Safety
406  
        Not thread-safe. Must not be called while any thread may
370  
        Not thread-safe. Must not be called while any thread may
407  
        be referencing this execution context or its executor.
371  
        be referencing this execution context or its executor.
408  

372  

409  
        @param mr Pointer to the memory resource.
373  
        @param mr Pointer to the memory resource.
410  

374  

411  
        @see get_frame_allocator
375  
        @see get_frame_allocator
412  
    */
376  
    */
413  
    void
377  
    void
414  
    set_frame_allocator(std::pmr::memory_resource* mr) noexcept
378  
    set_frame_allocator(std::pmr::memory_resource* mr) noexcept
415  
    {
379  
    {
416  
        owned_.reset();
380  
        owned_.reset();
417  
        frame_alloc_ = mr;
381  
        frame_alloc_ = mr;
418  
    }
382  
    }
419  

383  

420  
    /** Set the frame allocator from a standard Allocator.
384  
    /** Set the frame allocator from a standard Allocator.
421  

385  

422  
        The allocator is wrapped in an internal memory resource
386  
        The allocator is wrapped in an internal memory resource
423  
        adapter owned by this context. The wrapper remains valid
387  
        adapter owned by this context. The wrapper remains valid
424  
        for the lifetime of this context or until a subsequent
388  
        for the lifetime of this context or until a subsequent
425  
        call to set_frame_allocator.
389  
        call to set_frame_allocator.
426  

390  

427  
        @par Thread Safety
391  
        @par Thread Safety
428  
        Not thread-safe. Must not be called while any thread may
392  
        Not thread-safe. Must not be called while any thread may
429  
        be referencing this execution context or its executor.
393  
        be referencing this execution context or its executor.
430  

394  

431  
        @tparam Allocator The allocator type satisfying the
395  
        @tparam Allocator The allocator type satisfying the
432  
            standard Allocator requirements.
396  
            standard Allocator requirements.
433  

397  

434  
        @param a The allocator to use.
398  
        @param a The allocator to use.
435  

399  

436  
        @see get_frame_allocator
400  
        @see get_frame_allocator
437  
    */
401  
    */
438  
    template<class Allocator>
402  
    template<class Allocator>
439  
        requires (!std::is_pointer_v<Allocator>)
403  
        requires (!std::is_pointer_v<Allocator>)
440  
    void
404  
    void
441  
    set_frame_allocator(Allocator const& a)
405  
    set_frame_allocator(Allocator const& a)
442  
    {
406  
    {
443  
        static_assert(
407  
        static_assert(
444  
            requires { typename std::allocator_traits<Allocator>::value_type; },
408  
            requires { typename std::allocator_traits<Allocator>::value_type; },
445  
            "Allocator must satisfy allocator requirements");
409  
            "Allocator must satisfy allocator requirements");
446  
        static_assert(
410  
        static_assert(
447  
            std::is_copy_constructible_v<Allocator>,
411  
            std::is_copy_constructible_v<Allocator>,
448  
            "Allocator must be copy constructible");
412  
            "Allocator must be copy constructible");
449  

413  

450  
        auto p = std::make_shared<
414  
        auto p = std::make_shared<
451  
            detail::frame_memory_resource<Allocator>>(a);
415  
            detail::frame_memory_resource<Allocator>>(a);
452  
        frame_alloc_ = p.get();
416  
        frame_alloc_ = p.get();
453  
        owned_ = std::move(p);
417  
        owned_ = std::move(p);
454  
    }
418  
    }
455  

419  

456  
    /** Return a pointer to this context if it matches the
420  
    /** Return a pointer to this context if it matches the
457  
        requested type.
421  
        requested type.
458  

422  

459  
        Performs a type check and downcasts `this` when the
423  
        Performs a type check and downcasts `this` when the
460  
        types match, or returns `nullptr` otherwise. Analogous
424  
        types match, or returns `nullptr` otherwise. Analogous
461  
        to `std::any_cast< ExecutionContext >( &a )`.
425  
        to `std::any_cast< ExecutionContext >( &a )`.
462  

426  

463  
        @tparam ExecutionContext The derived context type to
427  
        @tparam ExecutionContext The derived context type to
464  
            retrieve.
428  
            retrieve.
465  

429  

466  
        @return A pointer to this context as the requested
430  
        @return A pointer to this context as the requested
467  
            type, or `nullptr` if the type does not match.
431  
            type, or `nullptr` if the type does not match.
468  
    */
432  
    */
469  
    template< typename ExecutionContext >
433  
    template< typename ExecutionContext >
470  
    const ExecutionContext* target() const
434  
    const ExecutionContext* target() const
471  
    {
435  
    {
472  
        if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
436  
        if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
473  
           return static_cast< ExecutionContext const* >( this );
437  
           return static_cast< ExecutionContext const* >( this );
474  
        return nullptr;
438  
        return nullptr;
475  
    }
439  
    }
476  

440  

477  
    /// @copydoc target() const
441  
    /// @copydoc target() const
478  
    template< typename ExecutionContext >
442  
    template< typename ExecutionContext >
479  
    ExecutionContext* target()
443  
    ExecutionContext* target()
480  
    {
444  
    {
481  
        if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
445  
        if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
482  
           return static_cast< ExecutionContext* >( this );
446  
           return static_cast< ExecutionContext* >( this );
483  
        return nullptr;
447  
        return nullptr;
484  
    }
448  
    }
485  

449  

486  
protected:
450  
protected:
487  
    /** Shut down all services.
451  
    /** Shut down all services.
488  

452  

489  
        Calls `shutdown()` on each service in reverse order of creation.
453  
        Calls `shutdown()` on each service in reverse order of creation.
490  
        After this call, services remain allocated but are in a stopped
454  
        After this call, services remain allocated but are in a stopped
491  
        state. Derived classes should call this in their destructor
455  
        state. Derived classes should call this in their destructor
492  
        before any members are destroyed. This function is idempotent;
456  
        before any members are destroyed. This function is idempotent;
493  
        subsequent calls have no effect.
457  
        subsequent calls have no effect.
494  

458  

495  
        @par Effects
459  
        @par Effects
496  
        Each service's `shutdown()` member function is invoked once.
460  
        Each service's `shutdown()` member function is invoked once.
497  

461  

498  
        @par Postconditions
462  
        @par Postconditions
499  
        @li All services are in a stopped state.
463  
        @li All services are in a stopped state.
500  

464  

501  
        @par Exception Safety
465  
        @par Exception Safety
502  
        No-throw guarantee.
466  
        No-throw guarantee.
503  

467  

504  
        @par Thread Safety
468  
        @par Thread Safety
505  
        Not thread-safe. Must not be called concurrently with other
469  
        Not thread-safe. Must not be called concurrently with other
506  
        operations on this execution_context.
470  
        operations on this execution_context.
507  
    */
471  
    */
508  
    void shutdown() noexcept;
472  
    void shutdown() noexcept;
509  

473  

510  
    /** Destroy all services.
474  
    /** Destroy all services.
511  

475  

512  
        Deletes all services in reverse order of creation. Derived
476  
        Deletes all services in reverse order of creation. Derived
513  
        classes should call this as the final step of destruction.
477  
        classes should call this as the final step of destruction.
514  
        This function is idempotent; subsequent calls have no effect.
478  
        This function is idempotent; subsequent calls have no effect.
515  

479  

516  
        @par Preconditions
480  
        @par Preconditions
517  
        @li `shutdown()` has been called.
481  
        @li `shutdown()` has been called.
518  

482  

519  
        @par Effects
483  
        @par Effects
520  
        All services are deleted and removed from the container.
484  
        All services are deleted and removed from the container.
521  

485  

522  
        @par Postconditions
486  
        @par Postconditions
523  
        @li The service container is empty.
487  
        @li The service container is empty.
524  

488  

525  
        @par Exception Safety
489  
        @par Exception Safety
526  
        No-throw guarantee.
490  
        No-throw guarantee.
527  

491  

528  
        @par Thread Safety
492  
        @par Thread Safety
529  
        Not thread-safe. Must not be called concurrently with other
493  
        Not thread-safe. Must not be called concurrently with other
530  
        operations on this execution_context.
494  
        operations on this execution_context.
531  
    */
495  
    */
532  
    void destroy() noexcept;
496  
    void destroy() noexcept;
533  

497  

534  
private:
498  
private:
535  
    struct BOOST_CAPY_DECL
499  
    struct BOOST_CAPY_DECL
536  
        factory
500  
        factory
537  
    {
501  
    {
538  
// warning C4251: 'std::type_index' needs to have dll-interface
502  
// warning C4251: 'std::type_index' needs to have dll-interface
539  
        BOOST_CAPY_MSVC_WARNING_PUSH
503  
        BOOST_CAPY_MSVC_WARNING_PUSH
540  
        BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
504  
        BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
541  
        detail::type_index t0;
505  
        detail::type_index t0;
542  
        detail::type_index t1;
506  
        detail::type_index t1;
543 -
        std::size_t slot0;
 
544 -
        std::size_t slot1;
 
545  
        BOOST_CAPY_MSVC_WARNING_POP
507  
        BOOST_CAPY_MSVC_WARNING_POP
546  

508  

547  
        factory(
509  
        factory(
548  
            detail::type_info const& t0_,
510  
            detail::type_info const& t0_,
549 -
            detail::type_info const& t1_,
511 +
            detail::type_info const& t1_)
550 -
            std::size_t s0,
 
551 -
            std::size_t s1)
 
552 -
            , slot0(s0), slot1(s1)
 
553  
            : t0(t0_), t1(t1_)
512  
            : t0(t0_), t1(t1_)
554  
        {
513  
        {
555  
        }
514  
        }
556  

515  

557  
        virtual service* create(execution_context&) = 0;
516  
        virtual service* create(execution_context&) = 0;
558  

517  

559  
    protected:
518  
    protected:
560  
        ~factory() = default;
519  
        ~factory() = default;
561  
    };
520  
    };
562  

521  

563  
    service* find_impl(detail::type_index ti) const noexcept;
522  
    service* find_impl(detail::type_index ti) const noexcept;
564  
    service& use_service_impl(factory& f);
523  
    service& use_service_impl(factory& f);
565  
    service& make_service_impl(factory& f);
524  
    service& make_service_impl(factory& f);
566  

525  

567 -
// warning C4251: std::mutex, std::shared_ptr, std::atomic need dll-interface
526 +
// warning C4251: std::mutex, std::shared_ptr need dll-interface
568  
    BOOST_CAPY_MSVC_WARNING_PUSH
527  
    BOOST_CAPY_MSVC_WARNING_PUSH
569  
    BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
528  
    BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
570  
    mutable std::mutex mutex_;
529  
    mutable std::mutex mutex_;
571  
    std::shared_ptr<void> owned_;
530  
    std::shared_ptr<void> owned_;
572  
    BOOST_CAPY_MSVC_WARNING_POP
531  
    BOOST_CAPY_MSVC_WARNING_POP
573  
    std::pmr::memory_resource* frame_alloc_ = nullptr;
532  
    std::pmr::memory_resource* frame_alloc_ = nullptr;
574  
    service* head_ = nullptr;
533  
    service* head_ = nullptr;
575 -

 
576 -
    static constexpr std::size_t max_service_slots = 32;
 
577 -
    BOOST_CAPY_MSVC_WARNING_PUSH
 
578 -
    BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
 
579 -
    std::atomic<service*> slots_[max_service_slots] = {};
 
580 -
    BOOST_CAPY_MSVC_WARNING_POP
 
581  
    bool shutdown_ = false;
534  
    bool shutdown_ = false;
582  
};
535  
};
583  

536  

584  
template< typename Derived >
537  
template< typename Derived >
585  
execution_context::
538  
execution_context::
586  
execution_context( Derived* ) noexcept
539  
execution_context( Derived* ) noexcept
587  
    : execution_context()
540  
    : execution_context()
588  
{
541  
{
589  
    ti_ = &detail::type_id< Derived >();
542  
    ti_ = &detail::type_id< Derived >();
590  
}
543  
}
591  

544  

592  
} // namespace capy
545  
} // namespace capy
593  
} // namespace boost
546  
} // namespace boost
594  

547  

595  
#endif
548  
#endif