LCOV - code coverage report
Current view: top level - capy/ex - execution_context.hpp (source / functions) Coverage Total Hit Missed
Test: coverage_remapped.info Lines: 100.0 % 52 52
Test Date: 2026-11-25 23:19:07 Functions: 95.3 % 150 143 7

           TLA  Line data    Source code
       1                 : //
       2                 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
       3                 : // Copyright (c) 2026 Michael Vandeberg
       4                 : //
       5                 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
       6                 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
       7                 : //
       8                 : // Official repository: https://github.com/cppalliance/capy
       9                 : //
      10                 : 
      11                 : #ifndef BOOST_CAPY_EXECUTION_CONTEXT_HPP
      12                 : #define BOOST_CAPY_EXECUTION_CONTEXT_HPP
      13                 : 
      14                 : #include <boost/capy/detail/config.hpp>
      15                 : #include <boost/capy/detail/frame_memory_resource.hpp>
      16                 : #include <boost/capy/detail/type_id.hpp>
      17                 : #include <boost/capy/concept/executor.hpp>
      18                 : #include <concepts>
      19                 : #include <memory>
      20                 : #include <memory_resource>
      21                 : #include <mutex>
      22                 : #include <tuple>
      23                 : #include <type_traits>
      24                 : #include <utility>
      25                 : 
      26                 : namespace boost {
      27                 : namespace capy {
      28                 : 
      29                 : /** Registers, looks up, and shuts down `service` objects owned by a derived context.
      30                 : 
      31                 :     An execution context represents a place where function objects are
      32                 :     executed. It provides a service registry where polymorphic services
      33                 :     can be stored and retrieved by type. Each service type may be stored
      34                 :     at most once. Services may specify a nested `key_type` to enable
      35                 :     lookup by a base class type.
      36                 : 
      37                 :     Derived classes such as `io_context` extend this to provide
      38                 :     execution facilities like event loops and thread pools. Derived
      39                 :     class destructors must call `shutdown()` and `destroy()` to ensure
      40                 :     proper service cleanup before member destruction. Between the two,
      41                 :     a context that queues work abandons what is still queued, including
      42                 :     work posted while it does so. A service created by an unwound chain
      43                 :     is shut down as it is created, so its work is taken too. Services
      44                 :     do not post from their destructors. A context may drain once more
      45                 :     after `destroy()`, so that stray work is still destroyed, but no
      46                 :     service may be created after `destroy()` returns.
      47                 : 
      48                 :     @par Service Lifecycle
      49                 :     Services are created on first use via `use_service()` or explicitly
      50                 :     via `make_service()`. During destruction, `shutdown()` is called on
      51                 :     each service in reverse order of creation, then `destroy()` deletes
      52                 :     them. Both functions are idempotent.
      53                 : 
      54                 :     @par Thread Safety
      55                 :     Service registration and lookup functions are thread-safe.
      56                 :     The `shutdown()` and `destroy()` functions are not thread-safe
      57                 :     and must only be called during destruction.
      58                 : 
      59                 :     @par Example
      60                 :     @par !example example
      61                 : 
      62                 : 
      63                 :     @see @ref service, @ref ExecutionContext
      64                 : */
      65                 : class BOOST_CAPY_DECL
      66                 :     execution_context
      67                 : {
      68                 :     detail::type_info const* ti_ = nullptr;
      69                 : 
      70                 :     template<class T, class = void>
      71                 :     struct get_key : std::false_type
      72                 :     {};
      73                 : 
      74                 :     template<class T>
      75                 :     struct get_key<T, std::void_t<typename T::key_type>> : std::true_type
      76                 :     {
      77                 :         using type = typename T::key_type;
      78                 :     };
      79                 : protected:
      80                 :     /** Construct from the most-derived context type.
      81                 : 
      82                 :         Records the dynamic type of the context so that
      83                 :         @ref target can later downcast `this` to the
      84                 :         requested derived type. Derived classes must pass
      85                 :         `this` typed as the most-derived type (i.e. invoke
      86                 :         this constructor from the most-derived class with
      87                 :         `this` of that type). Passing a pointer typed as a
      88                 :         base class records the wrong type and causes
      89                 :         `target<Derived>()` to return `nullptr`.
      90                 : 
      91                 :         @param self `this`, typed as the most-derived context type.
      92                 :             Only its type is recorded; the pointer is not stored.
      93                 :     */
      94                 :     template< typename Derived >
      95                 :     explicit execution_context( Derived* self ) noexcept;
      96                 : 
      97                 : public:
      98                 :     /** Gives a derived service a `shutdown()` hook, run when its owning `execution_context` is destroyed.
      99                 : 
     100                 :         Services provide extensible functionality to an execution context.
     101                 :         Each service type can be registered at most once. Services are
     102                 :         created via `use_service()` or `make_service()` and are owned by
     103                 :         the execution context for their lifetime.
     104                 : 
     105                 :         Derived classes must implement the pure virtual `shutdown()` member
     106                 :         function, which is called when the owning execution context is
     107                 :         being destroyed. The `shutdown()` function gives up all of the
     108                 :         service's work, releases resources and cancels outstanding
     109                 :         operations. It does not block, except to wait for work the
     110                 :         service already started. Such work includes its own threads or
     111                 :         operations it submitted to the system. Waiting ensures that
     112                 :         nothing that work posts arrives later. The destructor must not
     113                 :         post: by the time it runs, the context has already drained its
     114                 :         queue.
     115                 : 
     116                 :         @par Deriving from service
     117                 :         @li Implement `shutdown()` to perform cleanup.
     118                 :         @li Accept `execution_context&` as the first constructor parameter.
     119                 :         @li Optionally define `key_type` to enable base-class lookup.
     120                 : 
     121                 :         @par Example
     122                 :         @par !example example
     123                 : 
     124                 : 
     125                 :         @see @ref boost::capy::execution_context
     126                 :     */
     127                 :     class BOOST_CAPY_DECL
     128                 :         service
     129                 :     {
     130                 :     public:
     131                 :         /// Destroy the service.
     132 HIT        1090 :         virtual ~service() = default;
     133                 : 
     134                 :     protected:
     135                 :         /// Construct a service. Only derived classes may do so.
     136            1090 :         service() = default;
     137                 : 
     138                 :         /** Give up the service's work when the owning execution context shuts down.
     139                 : 
     140                 :             Implementations give up all of the service's work here,
     141                 :             release resources and cancel any outstanding asynchronous
     142                 :             operations, rather than in the destructor. This function
     143                 :             must not throw exceptions, and must not block except to
     144                 :             wait for work the service already started, such as threads
     145                 :             it owns. Services are shut down in
     146                 :             reverse order of creation. A service created after the
     147                 :             context shut down has this called as soon as it is created.
     148                 : 
     149                 :             @par Exception Safety
     150                 :             No-throw guarantee.
     151                 :         */
     152                 :         virtual void shutdown() = 0;
     153                 : 
     154                 :     private:
     155                 :         friend class execution_context;
     156                 : 
     157                 :         service* next_ = nullptr;
     158                 : 
     159                 : // warning C4251: 'std::type_index' needs to have dll-interface
     160                 :         BOOST_CAPY_MSVC_WARNING_PUSH
     161                 :         BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
     162                 :         detail::type_index t0_{detail::type_id<void>()};
     163                 :         detail::type_index t1_{detail::type_id<void>()};
     164                 :         BOOST_CAPY_MSVC_WARNING_POP
     165                 :     };
     166                 : 
     167                 :     /** Copy construction is disabled; a context owns its services.
     168                 : 
     169                 :         @param other The context that would be copied.
     170                 :     */
     171                 :     execution_context(execution_context const& other) = delete;
     172                 : 
     173                 :     /** Copy assignment is disabled; a context owns its services.
     174                 : 
     175                 :         @param other The context that would be assigned from.
     176                 : 
     177                 :         @return A reference to `*this`.
     178                 :     */
     179                 :     execution_context& operator=(execution_context const& other) = delete;
     180                 : 
     181                 :     /** Destroy the context, shutting down and deleting every service.
     182                 : 
     183                 :         Calls `shutdown()` then `destroy()` to clean up all services.
     184                 : 
     185                 :         @par Effects
     186                 :         All services are shut down and deleted in reverse order
     187                 :         of creation.
     188                 : 
     189                 :         @par Exception Safety
     190                 :         No-throw guarantee.
     191                 :     */
     192                 :     ~execution_context();
     193                 : 
     194                 :     /** Construct a default instance.
     195                 : 
     196                 :         @par Exception Safety
     197                 :         Strong guarantee.
     198                 :     */
     199                 :     execution_context();
     200                 : 
     201                 :     /** Check whether a service of type T exists.
     202                 : 
     203                 :         @par Thread Safety
     204                 :         Thread-safe.
     205                 : 
     206                 :         @tparam T The type of service to check.
     207                 : 
     208                 :         @return `true` if the service exists.
     209                 :     */
     210                 :     template<class T>
     211              16 :     bool has_service() const noexcept
     212                 :     {
     213              16 :         return find_service<T>() != nullptr;
     214                 :     }
     215                 : 
     216                 :     /** Return a pointer to the service of type T, or nullptr.
     217                 : 
     218                 :         @par Thread Safety
     219                 :         Thread-safe.
     220                 : 
     221                 :         @tparam T The type of service to find.
     222                 : 
     223                 :         @return A pointer to the service, or `nullptr` if not present.
     224                 :     */
     225                 :     template<class T>
     226              26 :     T* find_service() const noexcept
     227                 :     {
     228              26 :         std::lock_guard<std::mutex> lock(mutex_);
     229              26 :         return static_cast<T*>(find_impl(detail::type_id<T>()));
     230              26 :     }
     231                 : 
     232                 :     /** Return a reference to the service of type T, creating it if needed.
     233                 : 
     234                 :         If no service of type T exists, one is created by calling
     235                 :         `T(execution_context&)`. If T has a nested `key_type`, the
     236                 :         service is also indexed under that type.
     237                 : 
     238                 :         @par Constraints
     239                 :         @li `T` must derive from `service`.
     240                 :         @li `T` must be constructible from `execution_context&`.
     241                 : 
     242                 :         @par Exception Safety
     243                 :         Strong guarantee. If service creation throws, the container
     244                 :         is unchanged.
     245                 : 
     246                 :         @par Thread Safety
     247                 :         Thread-safe.
     248                 : 
     249                 :         @tparam T The type of service to retrieve or create.
     250                 : 
     251                 :         @return A reference to the service.
     252                 :     */
     253                 :     template<class T>
     254           12491 :     T& use_service()
     255                 :     {
     256                 :         static_assert(std::is_base_of<service, T>::value,
     257                 :             "T must derive from service");
     258                 :         static_assert(std::is_constructible<T, execution_context&>::value,
     259                 :             "T must be constructible from execution_context&");
     260                 : 
     261                 :         struct impl : factory
     262                 :         {
     263           12491 :             impl()
     264                 :                 : factory(
     265                 :                     detail::type_id<T>(),
     266                 :                     get_key<T>::value
     267                 :                         ? detail::type_id<typename get_key<T>::type>()
     268           12491 :                         : detail::type_id<T>())
     269                 :             {
     270           12491 :             }
     271                 : 
     272            1065 :             service* create(execution_context& ctx) override
     273                 :             {
     274            1065 :                 return new T(ctx);
     275                 :             }
     276                 :         };
     277                 : 
     278           12491 :         impl f;
     279           24982 :         return static_cast<T&>(use_service_impl(f));
     280                 :     }
     281                 : 
     282                 :     /** Construct and add a service.
     283                 : 
     284                 :         A new service of type T is constructed using the provided
     285                 :         arguments and added to the container. If T has a nested
     286                 :         `key_type`, the service is also indexed under that type.
     287                 : 
     288                 :         @par Constraints
     289                 :         @li `T` must derive from `service`.
     290                 :         @li `T` must be constructible from `execution_context&, Args...`.
     291                 :         @li If `T::key_type` exists, `T&` must be convertible to `key_type&`.
     292                 : 
     293                 :         @par Exception Safety
     294                 :         Strong guarantee. If service creation throws, the container
     295                 :         is unchanged.
     296                 : 
     297                 :         @par Thread Safety
     298                 :         Thread-safe.
     299                 : 
     300                 :         @throws std::invalid_argument if a service of the same type
     301                 :             or `key_type` already exists.
     302                 : 
     303                 :         @tparam T The type of service to create.
     304                 : 
     305                 :         @param args Arguments forwarded to the constructor of T.
     306                 : 
     307                 :         @return A reference to the created service.
     308                 :     */
     309                 :     template<class T, class... Args>
     310              28 :     T& make_service(Args&&... args)
     311                 :     {
     312                 :         static_assert(std::is_base_of<service, T>::value,
     313                 :             "T must derive from service");
     314                 :         if constexpr(get_key<T>::value)
     315                 :         {
     316                 :             static_assert(
     317                 :                 std::is_convertible<T&, typename get_key<T>::type&>::value,
     318                 :                 "T& must be convertible to key_type&");
     319                 :         }
     320                 : 
     321                 :         struct impl : factory
     322                 :         {
     323                 :             std::tuple<Args&&...> args_;
     324                 : 
     325              28 :             explicit impl(Args&&... a)
     326                 :                 : factory(
     327                 :                     detail::type_id<T>(),
     328                 :                     get_key<T>::value
     329                 :                         ? detail::type_id<typename get_key<T>::type>()
     330                 :                         : detail::type_id<T>())
     331              28 :                 , args_(std::forward<Args>(a)...)
     332                 :             {
     333              28 :             }
     334                 : 
     335              25 :             service* create(execution_context& ctx) override
     336                 :             {
     337              74 :                 return std::apply([&ctx](auto&&... a) {
     338              27 :                     return new T(ctx, std::forward<decltype(a)>(a)...);
     339              75 :                 }, std::move(args_));
     340                 :             }
     341                 :         };
     342                 : 
     343              28 :         impl f(std::forward<Args>(args)...);
     344              52 :         return static_cast<T&>(make_service_impl(f));
     345                 :     }
     346                 : 
     347                 :     /** Return the memory resource used for coroutine frame allocation.
     348                 : 
     349                 :         The returned pointer is valid for the lifetime of this context.
     350                 :         By default, this returns a pointer to the recycling memory
     351                 :         resource which pools frame allocations for reuse.
     352                 : 
     353                 :         @return Pointer to the frame allocator.
     354                 : 
     355                 :         @see @ref set_frame_allocator
     356                 :     */
     357                 :     std::pmr::memory_resource*
     358          103655 :     get_frame_allocator() const noexcept
     359                 :     {
     360          103655 :         return frame_alloc_;
     361                 :     }
     362                 : 
     363                 :     /** Set the memory resource used for coroutine frame allocation.
     364                 : 
     365                 :         The caller is responsible for ensuring the memory resource
     366                 :         remains valid for the lifetime of all coroutines started
     367                 :         using this context's executor.
     368                 : 
     369                 :         @par Thread Safety
     370                 :         Not thread-safe. Must not be called while any thread may
     371                 :         be referencing this execution context or its executor.
     372                 : 
     373                 :         @param mr Pointer to the memory resource.
     374                 : 
     375                 :         @see @ref get_frame_allocator
     376                 :     */
     377                 :     void
     378               1 :     set_frame_allocator(std::pmr::memory_resource* mr) noexcept
     379                 :     {
     380               1 :         owned_.reset();
     381               1 :         frame_alloc_ = mr;
     382               1 :     }
     383                 : 
     384                 :     /** Set the frame allocator from a standard Allocator.
     385                 : 
     386                 :         The allocator is wrapped in an internal memory resource
     387                 :         adapter owned by this context. The wrapper remains valid
     388                 :         for the lifetime of this context or until a subsequent
     389                 :         call to set_frame_allocator.
     390                 : 
     391                 :         @par Thread Safety
     392                 :         Not thread-safe. Must not be called while any thread may
     393                 :         be referencing this execution context or its executor.
     394                 : 
     395                 :         @par Exception Safety
     396                 :         Strong guarantee.
     397                 : 
     398                 :         @throws std::bad_alloc If memory allocation fails.
     399                 : 
     400                 :         @param a The allocator to use. Its type must satisfy the
     401                 :             standard Allocator requirements.
     402                 : 
     403                 :         @see @ref get_frame_allocator
     404                 :     */
     405                 :     template<class Allocator>
     406                 :         requires (!std::is_pointer_v<Allocator>)
     407                 :     void
     408            1430 :     set_frame_allocator(Allocator const& a)
     409                 :     {
     410                 :         static_assert(
     411                 :             requires { typename std::allocator_traits<Allocator>::value_type; },
     412                 :             "Allocator must satisfy allocator requirements");
     413                 :         static_assert(
     414                 :             std::is_copy_constructible_v<Allocator>,
     415                 :             "Allocator must be copy constructible");
     416                 : 
     417            1430 :         auto p = std::make_shared<
     418                 :             detail::frame_memory_resource<Allocator>>(a);
     419            1430 :         frame_alloc_ = p.get();
     420            1430 :         owned_ = std::move(p);
     421            1430 :     }
     422                 : 
     423                 :     /** Return a pointer to this context if it matches the
     424                 :         requested type.
     425                 : 
     426                 :         Performs a type check and downcasts `this` when the
     427                 :         types match, or returns `nullptr` otherwise. Analogous
     428                 :         to `std::any_cast< ExecutionContext >( &a )`.
     429                 : 
     430                 :         Returns `nullptr` unless the context was constructed through
     431                 :         the protected `Derived*` constructor with `Derived` equal to
     432                 :         `ExecutionContext`. A context built with the default
     433                 :         constructor always yields `nullptr`.
     434                 : 
     435                 :         @tparam ExecutionContext The derived context type to
     436                 :             retrieve.
     437                 : 
     438                 :         @return A pointer to this context as the requested
     439                 :             type, or `nullptr` if the type does not match.
     440                 :     */
     441                 :     template< typename ExecutionContext >
     442               2 :     const ExecutionContext* target() const
     443                 :     {
     444               2 :         if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
     445               1 :            return static_cast< ExecutionContext const* >( this );
     446               1 :         return nullptr;
     447                 :     }
     448                 : 
     449                 :     /// @copydoc target() const
     450                 :     template< typename ExecutionContext >
     451               2 :     ExecutionContext* target()
     452                 :     {
     453               2 :         if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
     454               1 :            return static_cast< ExecutionContext* >( this );
     455               1 :         return nullptr;
     456                 :     }
     457                 : 
     458                 : protected:
     459                 :     /** Shut down all services.
     460                 : 
     461                 :         Calls `shutdown()` on each service in reverse order of creation.
     462                 :         After this call, services remain allocated but are in a stopped
     463                 :         state. Derived classes must call this in their destructor
     464                 :         before any members are destroyed. This function is idempotent;
     465                 :         subsequent calls have no effect.
     466                 : 
     467                 :         @par Effects
     468                 :         Each service's `shutdown()` member function is invoked once. A
     469                 :         service created after this call has its `shutdown()` invoked as
     470                 :         soon as it is created, so it too starts in a stopped state.
     471                 : 
     472                 :         @par Postconditions
     473                 :         @li All services are in a stopped state.
     474                 : 
     475                 :         @par Exception Safety
     476                 :         No-throw guarantee.
     477                 : 
     478                 :         @par Thread Safety
     479                 :         Not thread-safe. Must not be called concurrently with other
     480                 :         operations on this execution_context.
     481                 :     */
     482                 :     void shutdown() noexcept;
     483                 : 
     484                 :     /** Destroy all services.
     485                 : 
     486                 :         Deletes all services in reverse order of creation. Derived
     487                 :         classes call this after giving up the work still queued, so
     488                 :         that work is destroyed while every service exists. This
     489                 :         function is idempotent; subsequent calls have no effect.
     490                 : 
     491                 :         @pre `shutdown()` was called.
     492                 :         @pre No service's destructor creates a service of a type
     493                 :             already destroyed here; two such destructors that re-create
     494                 :             each other never let this return.
     495                 : 
     496                 :         @par Effects
     497                 :         All services are deleted and removed from the container. Each
     498                 :         is removed just before it is deleted, so a destructor can still
     499                 :         find the services not yet destroyed. A service a destructor
     500                 :         creates is deleted in turn.
     501                 : 
     502                 :         @par Postconditions
     503                 :         @li The service container is empty.
     504                 : 
     505                 :         @par Exception Safety
     506                 :         No-throw guarantee.
     507                 : 
     508                 :         @par Thread Safety
     509                 :         Not thread-safe. Must not be called concurrently with other
     510                 :         operations on this execution_context.
     511                 : 
     512                 :         @note No service may be created after this returns. It would
     513                 :         outlive the derived context's members, which its destructor
     514                 :         may still reach. Debug builds check this when the context is
     515                 :         destroyed.
     516                 :     */
     517                 :     void destroy() noexcept;
     518                 : 
     519                 : private:
     520                 :     struct BOOST_CAPY_DECL
     521                 :         factory
     522                 :     {
     523                 : // warning C4251: 'std::type_index' needs to have dll-interface
     524                 :         BOOST_CAPY_MSVC_WARNING_PUSH
     525                 :         BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
     526                 :         detail::type_index t0;
     527                 :         detail::type_index t1;
     528                 :         BOOST_CAPY_MSVC_WARNING_POP
     529                 : 
     530           12519 :         factory(
     531                 :             detail::type_info const& t0_,
     532                 :             detail::type_info const& t1_)
     533           12519 :             : t0(t0_), t1(t1_)
     534                 :         {
     535           12519 :         }
     536                 : 
     537                 :         virtual service* create(execution_context&) = 0;
     538                 : 
     539                 :     protected:
     540                 :         ~factory() = default;
     541                 :     };
     542                 : 
     543                 :     service* find_impl(detail::type_index ti) const noexcept;
     544                 :     service& use_service_impl(factory& f);
     545                 :     service& make_service_impl(factory& f);
     546                 : 
     547                 : // warning C4251: std::mutex, std::shared_ptr need dll-interface
     548                 :     BOOST_CAPY_MSVC_WARNING_PUSH
     549                 :     BOOST_CAPY_MSVC_WARNING_DISABLE(4251)
     550                 :     mutable std::mutex mutex_;
     551                 :     std::shared_ptr<void> owned_;
     552                 :     BOOST_CAPY_MSVC_WARNING_POP
     553                 :     std::pmr::memory_resource* frame_alloc_ = nullptr;
     554                 :     service* head_ = nullptr;
     555                 :     bool shutdown_ = false;
     556                 :     bool destroyed_ = false;
     557                 : };
     558                 : 
     559                 : template< typename Derived >
     560            1058 : execution_context::
     561                 : execution_context( Derived* ) noexcept
     562            1058 :     : execution_context()
     563                 : {
     564            1058 :     ti_ = &detail::type_id< Derived >();
     565            1058 : }
     566                 : 
     567                 : } // namespace capy
     568                 : } // namespace boost
     569                 : 
     570                 : #endif
        

Generated by: LCOV version 2.3