diff --git a/.github/workflows/linux_release_modules.yml b/.github/workflows/linux_release_modules.yml index af27fcc568f2..d105d38270e8 100644 --- a/.github/workflows/linux_release_modules.yml +++ b/.github/workflows/linux_release_modules.yml @@ -38,6 +38,7 @@ jobs: -DHPX_WITH_VERIFY_LOCKS_BACKTRACE=ON \ -DHPX_WITH_CHECK_MODULE_DEPENDENCIES=ON \ -DHPX_WITH_CXX_MODULES=ON \ + -DHPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT=ON \ -DHPX_WITH_DATAPAR=ON \ -DHPX_WITH_DATAPAR_BACKEND=EMULATE base-targets: hpx_core core components diff --git a/.github/workflows/macos_debug.yml b/.github/workflows/macos_debug.yml index 477b711197fc..1914fdf5936b 100644 --- a/.github/workflows/macos_debug.yml +++ b/.github/workflows/macos_debug.yml @@ -41,6 +41,7 @@ jobs: -DHPX_WITH_CONTRACTS=ON \ -DHPX_WITH_CONTRACTS_MODE=ENFORCE \ -DHPX_WITH_TASK_SIZE_DEFAULT_PARAMETERS=ON \ + -DHPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT=ON \ -DHPX_WITH_TESTS_COMMAND_LINE=--hpx:queuing=local-priority-fifo-double base-targets: hpx_core core components # macOS runners are few, keep the number of parallel jobs low diff --git a/.github/workflows/windows_release_vs2022_modules.yml b/.github/workflows/windows_release_vs2022_modules.yml index 9f81376380e1..09870ef693c4 100644 --- a/.github/workflows/windows_release_vs2022_modules.yml +++ b/.github/workflows/windows_release_vs2022_modules.yml @@ -44,6 +44,7 @@ jobs: -DHPX_WITH_VERIFY_LOCKS_BACKTRACE=ON \ -DHPX_WITH_CHECK_MODULE_DEPENDENCIES=ON \ -DHPX_WITH_CXX_MODULES=ON \ + -DHPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT=ON \ -DHPX_WITH_DATAPAR=ON \ -DHPX_WITH_DATAPAR_BACKEND=EMULATE base-targets: hpx_core core components diff --git a/CMakeLists.txt b/CMakeLists.txt index 8290cd6b741b..f158ae00f404 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1013,6 +1013,19 @@ if(HPX_WITH_TASK_SIZE_DEFAULT_PARAMETERS) hpx_add_config_define(HPX_HAVE_TASK_SIZE_DEFAULT_PARAMETERS) endif() +hpx_option( + HPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT + BOOL + "Use a shared_suspending_fork_join_executor as the executor of the parallel execution policies par and par_unseq (default: OFF)" + OFF + CATEGORY "Thread Manager" + ADVANCED +) + +if(HPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT) + hpx_add_config_define(HPX_HAVE_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT) +endif() + hpx_option( HPX_WITH_COROUTINE_COUNTERS BOOL "Enable keeping track of coroutine creation and rebind counts (default: OFF)" diff --git a/docs/sphinx/manual/executors.rst b/docs/sphinx/manual/executors.rst index c4e9a6876532..3877246544a2 100644 --- a/docs/sphinx/manual/executors.rst +++ b/docs/sphinx/manual/executors.rst @@ -40,7 +40,7 @@ API. Main Executors in |hpx| ======================= -|hpx| provides multiple executors. Below are three of the most commonly used: +|hpx| provides multiple executors. Below are some of the most commonly used: Parallel Executor ----------------- @@ -92,6 +92,94 @@ Fork-Join Executor } ); +Suspending Fork-Join Executor +----------------------------- + +* Does the same job as the fork-join executor, but its waiting threads spin + only for a short time (the spin duration, 20 microseconds by default) and + then suspend until the next parallel region starts or the current one has + finished. +* Other work can run on the cores of an idle executor, and idle cores can go + to sleep. +* Constexpr default constructible; the worker threads are created on first + use. Copies made on an HPX thread share the worker threads of the original. +* The calling thread takes part in the parallel regions if it runs on one of + the executor's PUs; otherwise it suspends until the region has finished. + +.. code-block:: c++ + + #include + #include + + std::vector data(100, 1); + + hpx::execution::experimental::suspending_fork_join_executor exec; + + hpx::for_each( + hpx::execution::par.on(exec), + data.begin(), data.end(), + [](int &x) { + x += 1; + } + ); + +A ``suspending_fork_join_executor`` can't be used from several threads at the +same time or from inside one of its own parallel regions (nested +parallelism). ``shared_suspending_fork_join_executor`` can: + +* All ``shared_suspending_fork_join_executor`` objects with the same + configuration (priority, stack size, loop schedule and spin duration) share + one set of worker threads per thread pool. It is created when an |hpx| + thread of the pool uses such an executor first, and stopped when the + runtime starts to shut down. +* A parallel region runs on these worker threads if they are free. If they are + busy, because they run a region for another thread or because the region is + started from inside one of their regions, the region runs through a + ``parallel_executor`` instead: one task for each worker thread of the pool, + each with a contiguous range of the indices. The same happens if the calling + thread is not an |hpx| thread, and once the worker threads were stopped. +* Exceptions are reported by whichever executor ran the region: the first + exception from the worker threads, or an ``hpx::exception_list`` from the + ``parallel_executor``. +* As with ``suspending_fork_join_executor``, asynchronous calls + (``bulk_async_execute``, ``async_invoke``) run the region before they + return a ready future. +* Single tasks (``sync_execute``, ``async_execute``, ``then_execute``, + ``post``) and continuations (``bulk_then_execute``) run as a + ``parallel_executor`` runs them. +* Copies never own worker threads, so the executor can be a ``constexpr`` + variable. + +If |hpx| is configured with +``HPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT=ON`` (default: ``OFF``), +``shared_suspending_fork_join_executor`` is the executor of the parallel +execution policies ``par`` and ``par_unseq``, instead of +``parallel_executor``. The task policies ``par(task)`` and +``par_unseq(task)`` keep using ``parallel_executor``: they run an algorithm +asynchronously, which the worker threads of a fork-join executor can't do. +For the same reason, mapping a policy with a +``shared_suspending_fork_join_executor`` to a task policy (``to_task``, as in +``par(task)`` or ``par.on(exec)(task)``) gives it a ``parallel_executor``. + +.. code-block:: c++ + + #include + #include + + std::vector data(100, 1); + + // can be used by any number of threads, also from inside the loop body + constexpr hpx::execution::experimental::shared_suspending_fork_join_executor + exec; + + hpx::for_each( + hpx::execution::par.on(exec), + data.begin(), data.end(), + [](int &x) { + x += 1; + } + ); + Sequential Executor ------------------- diff --git a/libs/core/executors/CMakeLists.txt b/libs/core/executors/CMakeLists.txt index fd058c9185ba..3434b451490b 100644 --- a/libs/core/executors/CMakeLists.txt +++ b/libs/core/executors/CMakeLists.txt @@ -42,6 +42,7 @@ set(executors_headers hpx/executors/scheduler_executor.hpp hpx/executors/sequenced_executor.hpp hpx/executors/service_executors.hpp + hpx/executors/suspending_fork_join_executor.hpp hpx/executors/std_execution_policy.hpp hpx/executors/sync.hpp hpx/executors/task.hpp @@ -105,8 +106,12 @@ endif() # cmake-format: on set(executors_sources - current_executor.cpp exception_list_callbacks.cpp fork_join_executor.cpp - parallel_scheduler.cpp service_executors.cpp + current_executor.cpp + exception_list_callbacks.cpp + fork_join_executor.cpp + parallel_scheduler.cpp + service_executors.cpp + suspending_fork_join_executor.cpp ) include(HPX_AddModule) diff --git a/libs/core/executors/include/hpx/executors/execution_policy.hpp b/libs/core/executors/include/hpx/executors/execution_policy.hpp index 0227d32c81b7..4154eb002572 100644 --- a/libs/core/executors/include/hpx/executors/execution_policy.hpp +++ b/libs/core/executors/include/hpx/executors/execution_policy.hpp @@ -17,6 +17,9 @@ #include #include #include +#if defined(HPX_HAVE_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT) +#include +#endif #include #include #include @@ -40,6 +43,15 @@ namespace hpx::execution { typename Executor, typename Parameters = void, typename Category = void> struct execution_policy; + + // The executor of the parallel policy and the parallel unsequenced + // policy. The task policies always use parallel_executor. +#if defined(HPX_HAVE_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT) + using default_parallel_executor = + hpx::execution::experimental::shared_suspending_fork_join_executor; +#else + using default_parallel_executor = parallel_executor; +#endif } // namespace detail /////////////////////////////////////////////////////////////////////////// @@ -737,8 +749,9 @@ namespace hpx::execution { /// type to disambiguate parallel algorithm overloading and indicate that a /// parallel algorithm's execution may be parallelized. HPX_CXX_CORE_EXPORT using parallel_policy = - detail::parallel_policy_shim>; + detail::parallel_policy_shim>; /// Default parallel execution policy object. HPX_CXX_CORE_EXPORT inline constexpr parallel_policy par{}; @@ -903,8 +916,10 @@ namespace hpx::execution { /// indicate that a parallel algorithm's execution may be parallelized and /// vectorized. HPX_CXX_CORE_EXPORT using parallel_unsequenced_policy = - detail::parallel_unsequenced_policy_shim>; + detail::parallel_unsequenced_policy_shim< + detail::default_parallel_executor, + hpx::traits::executor_parameters_type_t< + detail::default_parallel_executor>>; /// Default vector execution policy object. HPX_CXX_CORE_EXPORT inline constexpr parallel_unsequenced_policy diff --git a/libs/core/executors/include/hpx/executors/suspending_fork_join_executor.hpp b/libs/core/executors/include/hpx/executors/suspending_fork_join_executor.hpp new file mode 100644 index 000000000000..1bfc71569c69 --- /dev/null +++ b/libs/core/executors/include/hpx/executors/suspending_fork_join_executor.hpp @@ -0,0 +1,1112 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +/// \file suspending_fork_join_executor.hpp + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace hpx::execution::experimental { + + namespace detail { + + // A std::shared_ptr that is constructed only when a pointer is + // assigned to it. A class that holds it can be constexpr constructed + // and destructed (std::shared_ptr's destructor is not constexpr), also + // as a mutable member. + template + class lazy_shared_ptr + { + public: + constexpr lazy_shared_ptr() noexcept = default; + + constexpr lazy_shared_ptr(lazy_shared_ptr const& rhs) noexcept + { + if (rhs.engaged_) + { + ::new (address()) std::shared_ptr(*rhs.ptr()); + engaged_ = true; + } + } + + constexpr lazy_shared_ptr(lazy_shared_ptr&& rhs) noexcept + { + if (rhs.engaged_) + { + ::new (address()) std::shared_ptr(HPX_MOVE(*rhs.ptr())); + engaged_ = true; + } + } + + constexpr lazy_shared_ptr& operator=( + lazy_shared_ptr const& rhs) noexcept + { + if (this != &rhs) + { + reset(); + if (rhs.engaged_) + { + ::new (address()) std::shared_ptr(*rhs.ptr()); + engaged_ = true; + } + } + return *this; + } + + constexpr lazy_shared_ptr& operator=(lazy_shared_ptr&& rhs) noexcept + { + if (this != &rhs) + { + reset(); + if (rhs.engaged_) + { + ::new (address()) + std::shared_ptr(HPX_MOVE(*rhs.ptr())); + engaged_ = true; + } + } + return *this; + } + + // A constant expression never engages it. It may not even read + // engaged_ then, if it is a mutable member. + constexpr ~lazy_shared_ptr() + { + if (!std::is_constant_evaluated()) + { + reset(); + } + } + + void assign(std::shared_ptr p) noexcept + { + reset(); + ::new (address()) std::shared_ptr(HPX_MOVE(p)); + engaged_ = true; + } + + constexpr void reset() noexcept + { + if (engaged_) + { + std::destroy_at(ptr()); + engaged_ = false; + } + } + + [[nodiscard]] constexpr T* get() const noexcept + { + return engaged_ ? ptr()->get() : nullptr; + } + + [[nodiscard]] std::shared_ptr shared() const noexcept + { + return engaged_ ? *ptr() : std::shared_ptr(); + } + + private: + void* address() noexcept + { + return static_cast(storage_); + } + + std::shared_ptr* ptr() const noexcept + { + return std::launder(reinterpret_cast*>( + const_cast(storage_))); + } + + // holds a std::shared_ptr if engaged_ + alignas(std::shared_ptr) unsigned char storage_[sizeof( + std::shared_ptr)] = {}; + bool engaged_ = false; + }; + } // namespace detail + + /// \brief An executor with fork-join (blocking) semantics whose waiting + /// threads suspend instead of spinning. + /// + /// The suspending_fork_join_executor does the same job as the + /// fork_join_executor: it runs each parallel region on a fixed set of + /// worker threads, one per processing unit (PU), and the calling thread + /// takes part in the region if it runs on one of these PUs. Its waiting + /// threads (the workers between two regions and the caller at the end of + /// a region) spin for a short time only (the spin duration), and then + /// suspend until they are woken up. Other work can run on their cores + /// meanwhile, and idle cores can go to sleep. + /// + /// The executor is constexpr default constructible. It creates its worker + /// threads on first use, on the pool of the thread that uses it first (or + /// the default pool). Copies have reference semantics: copying an + /// executor on an HPX thread creates the worker threads first if needed, + /// and the copy shares them. Copies made before the HPX runtime runs (or + /// on a thread that is not an HPX thread) share nothing with the + /// original until it is used; each of them creates its own worker threads + /// on first use. The worker threads exit when the last copy that shares + /// them is destroyed, or when the runtime starts to shut down (in + /// hpx::finalize, see hpx::register_pre_shutdown_function), whichever + /// comes first: suspended threads would keep the runtime from stopping. + /// Using the executor after its worker threads exited throws + /// invalid_status. + /// + /// The calling thread takes part in the parallel regions if, when the + /// worker threads are created, it is a worker thread of the same pool + /// running on a PU in the executor's PU mask. Otherwise all PUs get a + /// worker thread, and the calling thread suspends until the region has + /// finished. Scheduling work through the executor concurrently from + /// different threads, or from inside one of its own parallel regions, is + /// not supported. shared_suspending_fork_join_executor lifts these + /// restrictions. + HPX_CXX_CORE_EXPORT class suspending_fork_join_executor + { + public: + /// Type of loop schedule, see fork_join_executor::loop_schedule. + using loop_schedule = fork_join_executor::loop_schedule; + + /// \cond NOINTERNAL + using execution_category = hpx::execution::parallel_execution_tag; + using executor_parameters_type = + hpx::execution::experimental::default_parameters; + /// \endcond + + /// The default time the waiting threads spin before they suspend. + static constexpr std::chrono::nanoseconds default_spin_duration = + std::chrono::microseconds(20); + + private: + /// \cond NOINTERNAL + + // The state shared by all copies of an executor and by its worker + // threads. It is created on first use. + struct HPX_CORE_EXPORT shared_data + { + using region_function_type = void( + void*, shared_data&, std::size_t) noexcept; + using queue_type = + hpx::concurrency::detail::contiguous_index_queue; + + shared_data(threads::thread_priority priority, + threads::thread_stacksize stacksize, loop_schedule sched, + std::chrono::nanoseconds spin_duration, + hpx::threads::mask_type const* pu_mask, char const* annotation); + + shared_data(shared_data const&) = delete; + shared_data(shared_data&&) = delete; + shared_data& operator=(shared_data const&) = delete; + shared_data& operator=(shared_data&&) = delete; + + ~shared_data(); + + // Run one parallel region of size indices: f(body, data, slot) + // runs the share of the given slot. + void execute_region( + region_function_type* f, void* body, std::size_t size); + + // Run one parallel region as execute_region does, if the worker + // threads are free: returns false, and does nothing, if they run + // a region already (another one, or the one this is called from) + // or if they have exited. + bool try_execute_region( + region_function_type* f, void* body, std::size_t size); + + // Run the share of the given slot of the current region, calling + // body(first, last) for ranges of its indices. + template + void run_share(std::size_t const slot, Body& body) noexcept + { + hpx::detail::try_catch_exception_ptr( + [&] { + if (dynamic_) + { + // Items are taken in chunks of 1/num_threads of + // the items left in a queue (but at least one), + // one atomic operation per chunk. The chunks + // shrink as a queue drains, so the other slots + // can still take a share of an unevenly loaded + // queue. + auto const divisor = + static_cast(num_threads_); + hpx::optional< + std::pair> + chunk; + + // process the own items first + queue_type& local_queue = queues_[slot].data_; + while ( + (chunk = local_queue.pop_left_chunk(divisor))) + { + body(static_cast(chunk->first), + static_cast(chunk->second)); + } + + // then steal from the other slots + for (std::size_t offset = 1; offset != num_threads_; + ++offset) + { + queue_type& queue = + queues_[(slot + offset) % num_threads_] + .data_; + while ((chunk = queue.pop_right_chunk(divisor))) + { + body(static_cast(chunk->first), + static_cast( + chunk->second)); + } + } + } + else + { + std::size_t const size = region_size_; + body((slot * size) / num_threads_, + ((slot + 1) * size) / num_threads_); + } + }, + [&](std::exception_ptr&& ep) { + store_exception(HPX_MOVE(ep)); + }); + } + + void store_exception(std::exception_ptr&& ep) noexcept; + + // the main loop of a worker thread, position is its place in the + // wake-up tree + void worker_main(std::size_t slot, std::size_t position) noexcept; + + // Wake the worker threads and wait until they have exited. The + // executor can't be used afterwards. This is done by the + // destructor, and when the runtime starts to shut down: it can't + // stop while the worker threads are suspended. + void stop_workers() noexcept; + + // Stop the worker threads of the given shared data when the + // runtime starts to shut down, if it still exists then. + static void stop_on_shutdown(std::weak_ptr data); + + // the shared data registered with stop_on_shutdown, and the + // shared instances (see shared_suspending_fork_join_executor) + struct shutdown_registry; + + // Members that are fixed for the lifetime of the executor. + threads::thread_pool_base* pool_ = nullptr; + threads::thread_priority priority_; + threads::thread_stacksize stacksize_; + loop_schedule schedule_; + std::uint64_t spin_rounds_ = 0; + std::size_t num_threads_ = 0; + std::size_t num_workers_ = 0; + std::size_t caller_slot_ = static_cast(-1); + hpx::threads::mask_type pu_mask_; + + // Members that change for each parallel region. They are written + // by the calling thread before it starts the region. + region_function_type* region_function_ = nullptr; + void* region_body_ = nullptr; + std::size_t region_size_ = 0; + bool dynamic_ = false; + + // Set while a region runs, and once the worker threads were + // stopped. + std::atomic in_region_ = false; + + hpx::spinlock exception_mtx_; + std::exception_ptr exception_; + + // the queues for dynamic scheduling, one per slot + std::vector> queues_; + + // Incremented for each parallel region (and to stop the worker + // threads). + hpx::util::cache_aligned_data> epoch_; + std::atomic stop_ = false; + + // set once the worker threads were asked to stop + std::atomic stopped_ = false; + + // the number of worker threads that still work on the current + // region + hpx::util::cache_aligned_data> remaining_; + + // the number of worker threads that have not exited yet + std::atomic alive_ = 0; + + // Where a worker thread suspends while it waits for a new region. + // Each one has its own, so that the suspended worker threads are + // woken in a tree (see wake_workers) instead of all by the + // calling thread. + struct parking + { + hpx::spinlock mtx; + hpx::lcos::local::detail::condition_variable cv; + std::atomic parked = false; + }; + std::unique_ptr[]> parking_; + + // The calling thread suspends on this condition variable when it + // waits for the worker threads to finish a region. + hpx::spinlock caller_mtx_; + hpx::lcos::local::detail::condition_variable caller_cv_; + std::atomic caller_parked_ = false; + + private: + void publish_region() noexcept; + void wake_workers(std::size_t first) noexcept; + bool wait_for_region( + std::uint64_t seen, std::size_t position) noexcept; + void finish_share() noexcept; + void wait_for_workers() noexcept; + void init_threads(char const* annotation); + void run_locked_region( + region_function_type* f, void* body, std::size_t size); + }; + + template + static void call_region( + void* body, shared_data& data, std::size_t const slot) noexcept + { + data.run_share(slot, *static_cast(body)); + } + + template + static decltype(auto) invoke_element( + hpx::util::index_pack, F& f, A&& a, Tuple& t) + { + return HPX_INVOKE(f, HPX_FORWARD(A, a), hpx::get(t)...); + } + + // Create the shared data, if needed. + shared_data& data() const + { + if (!shared_data_.get()) + { + auto data = std::make_shared(priority_, stacksize_, + schedule_, spin_duration_, pu_mask_.get(), annotation_); + shared_data::stop_on_shutdown(data); + shared_data_.assign(HPX_MOVE(data)); + } + return *shared_data_.get(); + } + + // The shared data a copy of this executor refers to. A shared + // executor never holds any (see shared_instance). + std::shared_ptr data_for_copy() const + { + if (!shared_ && !shared_data_.get() && + threads::get_self_id_data() != nullptr) + { + (void) data(); + } + return shared_data_.shared(); + } + + // The shared data of a shared executor: the one instance for the + // pool of the calling thread and the configuration of this executor. + // Returns nullptr if the calling thread is not an HPX thread, or if + // it can't be created. + HPX_CORE_EXPORT std::shared_ptr shared_instance() + const noexcept; + + template + void run_region(Body& body, std::size_t const size) const + { + if (shared_) + { + // Use the shared instance if it is free, run the region + // through a parallel_executor otherwise. + if (auto const data = shared_instance(); data && + data->try_execute_region(&call_region, &body, size)) + { + return; + } + run_fallback_region(body, size); + return; + } + data().execute_region(&call_region, &body, size); + } + + // Run a region through a parallel_executor: one task per worker + // thread of the pool, each with a contiguous range of indices. + template + static void run_fallback_region(Body& body, std::size_t const size) + { + if (size == 0) + { + return; + } + + std::size_t const num_chunks = (std::min) (size, + (std::max) (std::size_t(1), + threads::detail::get_self_or_default_pool() + ->get_os_thread_count())); + + hpx::execution::parallel_executor const exec{}; + hpx::parallel::execution::bulk_sync_execute( + exec, + [&](std::size_t const chunk) { + body((chunk * size) / num_chunks, + ((chunk + 1) * size) / num_chunks); + }, + hpx::util::counting_shape(num_chunks)); + } + + template + void sync_invoke_impl(Fs&&... fs) const + { +#if defined(HPX_HAVE_THREAD_DESCRIPTION) + hpx::scoped_annotation annotate(annotation_ ? + annotation_ : + "suspending_fork_join_executor::sync_invoke"); +#endif + auto function_pack = hpx::forward_as_tuple(HPX_FORWARD(Fs, fs)...); + auto body = [&](std::size_t first, std::size_t const last) { + for (/**/; first != last; ++first) + { + hpx::visit([](auto&& f) { HPX_INVOKE(f); }, + hpx::detail::runtime_get(function_pack, first)); + } + }; + run_region(body, sizeof...(Fs)); + } + + template + void post(F&& f, Ts&&... ts) const + { + (void) async_invoke( + hpx::bind_back(HPX_FORWARD(F, f), HPX_FORWARD(Ts, ts)...)); + } + + HPX_CORE_EXPORT static hpx::threads::mask_type default_pu_mask(); + /// \endcond + + public: + /// \cond NOINTERNAL + template + requires(!std::is_integral_v) + decltype(auto) bulk_sync_execute( + F&& f, S const& shape, Ts&&... ts) const + { + HPX_TRACING_MARK_EVENT( + "suspending_fork_join_executor::bulk_sync_execute"); + +#if defined(HPX_HAVE_THREAD_DESCRIPTION) + hpx::scoped_annotation annotate(annotation_ ? + annotation_ : + "suspending_fork_join_executor::bulk_sync_execute"); +#endif + using result_type = + hpx::parallel::execution::detail::bulk_execute_result_t; + using index_pack_type = hpx::util::make_index_pack_t; + + auto argument_pack = hpx::forward_as_tuple(HPX_FORWARD(Ts, ts)...); + auto const first = hpx::util::begin(shape); + using difference_type = typename std::iterator_traits< + std::decay_t>::difference_type; + + std::size_t const size = hpx::util::size(shape); + if constexpr (std::is_void_v) + { + auto body = [&](std::size_t i, std::size_t const last) { + auto it = std::next(first, static_cast(i)); + for (/**/; i != last; ++i, ++it) + { + invoke_element( + index_pack_type{}, f, *it, argument_pack); + } + }; + run_region(body, size); + } + else + { + result_type results(size); + auto body = [&](std::size_t i, std::size_t const last) { + auto it = std::next(first, static_cast(i)); + for (/**/; i != last; ++i, ++it) + { + results[i] = invoke_element( + index_pack_type{}, f, *it, argument_pack); + } + }; + run_region(body, size); + return results; + } + } + + template + requires(!std::is_integral_v) + decltype(auto) bulk_async_execute( + F&& f, S const& shape, Ts&&... ts) const + { + using result_type = + hpx::parallel::execution::detail::bulk_execute_result_t; + + // Forward to the synchronous version: this thread takes part in + // the region, so the future can be made ready only at its end. + return hpx::detail::try_catch_exception_ptr( + [&]() { + if constexpr (std::is_void_v) + { + bulk_sync_execute( + HPX_FORWARD(F, f), shape, HPX_FORWARD(Ts, ts)...); + return hpx::make_ready_future(); + } + else + { + auto&& result = bulk_sync_execute( + HPX_FORWARD(F, f), shape, HPX_FORWARD(Ts, ts)...); + return hpx::make_ready_future(HPX_MOVE(result)); + } + }, + [&](std::exception_ptr&& ep) { + return hpx::make_exceptional_future( + HPX_MOVE(ep)); + }); + } + + template + requires(std::invocable && (std::invocable && ...)) + void sync_invoke(F&& f, Fs&&... fs) const + { + sync_invoke_impl(HPX_FORWARD(F, f), HPX_FORWARD(Fs, fs)...); + } + + template + requires(std::invocable && (std::invocable && ...)) + hpx::future async_invoke(F&& f, Fs&&... fs) const + { + return hpx::detail::try_catch_exception_ptr( + [&]() { + sync_invoke_impl(HPX_FORWARD(F, f), HPX_FORWARD(Fs, fs)...); + return hpx::make_ready_future(); + }, + [&](std::exception_ptr&& ep) { + return hpx::make_exceptional_future(HPX_MOVE(ep)); + }); + } + + bool operator==(suspending_fork_join_executor const& rhs) const noexcept + { + if (shared_ != rhs.shared_ || priority_ != rhs.priority_ || + stacksize_ != rhs.stacksize_ || schedule_ != rhs.schedule_ || + spin_duration_ != rhs.spin_duration_) + { + return false; + } + auto const* lhs_mask = pu_mask_.get(); + auto const* rhs_mask = rhs.pu_mask_.get(); + if (lhs_mask == rhs_mask) + { + return true; + } + return lhs_mask && rhs_mask && *lhs_mask == *rhs_mask; + } + + bool operator!=(suspending_fork_join_executor const& rhs) const noexcept + { + return !(*this == rhs); + } + + [[nodiscard]] suspending_fork_join_executor const& context() + const noexcept + { + return *this; + } + /// \endcond + + /// \brief Construct a suspending_fork_join_executor that uses all PUs + /// of the pool. The worker threads are created on first use. + /// + /// \param priority The priority of the worker threads. + /// \param stacksize The stacksize of the worker threads. It can't be + /// thread_stacksize::nostack, as the worker threads suspend. + /// \param sched The loop schedule of the parallel regions. + /// \param spin_duration The time a waiting thread spins before it + /// suspends. + explicit constexpr suspending_fork_join_executor( + threads::thread_priority priority = threads::thread_priority::bound, + threads::thread_stacksize stacksize = + threads::thread_stacksize::small_, + loop_schedule sched = loop_schedule::dynamic, + std::chrono::nanoseconds spin_duration = + default_spin_duration) noexcept + : spin_duration_(spin_duration) + , priority_(priority) + , stacksize_(stacksize) + , schedule_(sched) + { + } + + /// \brief Construct a suspending_fork_join_executor that uses the + /// given PUs. The worker threads are created on first use. + /// + /// \param pu_mask The PUs to use for the worker threads. + /// \param priority The priority of the worker threads. + /// \param stacksize The stacksize of the worker threads. It can't be + /// thread_stacksize::nostack, as the worker threads suspend. + /// \param sched The loop schedule of the parallel regions. + /// \param spin_duration The time a waiting thread spins before it + /// suspends. + explicit suspending_fork_join_executor( + hpx::threads::mask_cref_type pu_mask, + threads::thread_priority priority = threads::thread_priority::bound, + threads::thread_stacksize stacksize = + threads::thread_stacksize::small_, + loop_schedule sched = loop_schedule::dynamic, + std::chrono::nanoseconds spin_duration = default_spin_duration) + : spin_duration_(spin_duration) + , priority_(priority) + , stacksize_(stacksize) + , schedule_(sched) + { + pu_mask_.assign( + std::make_shared(pu_mask)); + } + + /// \brief Copy an executor. Copying on an HPX thread creates the + /// worker threads of \a rhs first, if needed, and the copy + /// shares them. + constexpr suspending_fork_join_executor( + suspending_fork_join_executor const& rhs) + : pu_mask_(rhs.pu_mask_) + , annotation_(rhs.annotation_) + , spin_duration_(rhs.spin_duration_) + , priority_(rhs.priority_) + , stacksize_(rhs.stacksize_) + , schedule_(rhs.schedule_) + , shared_(rhs.shared_) + { + if (!std::is_constant_evaluated()) + { + copy_data_from(rhs); + } + } + + suspending_fork_join_executor( + suspending_fork_join_executor&&) noexcept = default; + + constexpr suspending_fork_join_executor& operator=( + suspending_fork_join_executor const& rhs) + { + if (this != &rhs) + { + if (std::is_constant_evaluated()) + { + shared_data_.reset(); + } + else + { + copy_data_from(rhs); + } + pu_mask_ = rhs.pu_mask_; + annotation_ = rhs.annotation_; + spin_duration_ = rhs.spin_duration_; + priority_ = rhs.priority_; + stacksize_ = rhs.stacksize_; + schedule_ = rhs.schedule_; + shared_ = rhs.shared_; + } + return *this; + } + + suspending_fork_join_executor& operator=( + suspending_fork_join_executor&&) noexcept = default; + + constexpr ~suspending_fork_join_executor() = default; + + /// \cond NOINTERNAL + [[nodiscard]] suspending_fork_join_executor query( + experimental::with_annotation_t, char const* annotation) const + { + auto exec_with_annotation = *this; + exec_with_annotation.annotation_ = annotation; + return exec_with_annotation; + } + + [[nodiscard]] suspending_fork_join_executor query( + experimental::with_annotation_t, std::string annotation) const + { + auto exec_with_annotation = *this; + exec_with_annotation.annotation_ = + hpx::detail::store_function_annotation(HPX_MOVE(annotation)); + return exec_with_annotation; + } + + [[nodiscard]] char const* query( + experimental::get_annotation_t) const noexcept + { + return annotation_; + } + + [[nodiscard]] hpx::threads::mask_type query( + experimental::get_processing_units_mask_t) const + { + if (auto const* data = shared_data_.get()) + { + return data->pu_mask_; + } + auto const* mask = pu_mask_.get(); + return mask ? *mask : default_pu_mask(); + } + + [[nodiscard]] hpx::threads::mask_type query( + experimental::get_cores_mask_t) const + { + return query(experimental::get_processing_units_mask_t{}); + } + + [[nodiscard]] std::size_t query(experimental::get_first_core_t) const + { + auto const mask = + query(experimental::get_processing_units_mask_t{}); + auto const size = hpx::threads::mask_size(mask); + for (std::size_t i = 0; i != size; ++i) + { + if (hpx::threads::test(mask, i)) + return i; + } + return 0; + } + + template + requires(hpx::executor_parameters) + [[nodiscard]] std::size_t query(experimental::processing_units_count_t, + Parameters&& params, + hpx::chrono::steady_duration const& iter_dur = + hpx::chrono::null_duration, + std::size_t num_tasks = 0) const + { + using exec_type = std::decay_t; + if constexpr (requires(std::decay_t const& p, + exec_type const& e, + hpx::chrono::steady_duration const& d) { + p.processing_units_count(e, d, std::size_t{}); + }) + { + return HPX_FORWARD(Parameters, params) + .processing_units_count(*this, iter_dur, num_tasks); + } + else + { + if (auto const* data = shared_data_.get()) + { + return data->num_threads_; + } + return hpx::threads::count( + query(experimental::get_processing_units_mask_t{})); + } + } + + /// P2300 get_scheduler bridge + hpx::execution::experimental::executor_scheduler< + suspending_fork_join_executor> + query(hpx::execution::experimental::get_scheduler_t) const noexcept + { + // The scheduler shares the worker threads, unless they can't be + // created now; it then creates its own on first use. + hpx::detail::try_catch_exception_ptr( + [&] { (void) data_for_copy(); }, [](std::exception_ptr&&) {}); + return hpx::execution::experimental::executor_scheduler< + suspending_fork_join_executor>( + suspending_fork_join_executor(*this, no_init)); + } + /// \endcond + + protected: + /// \cond NOINTERNAL + enum class shared_t : std::uint8_t + { + shared + }; + + // a shared executor, see shared_suspending_fork_join_executor + explicit constexpr suspending_fork_join_executor(shared_t, + threads::thread_priority priority, + threads::thread_stacksize stacksize, loop_schedule sched, + std::chrono::nanoseconds spin_duration) noexcept + : spin_duration_(spin_duration) + , priority_(priority) + , stacksize_(stacksize) + , schedule_(sched) + , shared_(true) + { + } + /// \endcond + + private: + void copy_data_from(suspending_fork_join_executor const& rhs) + { + if (auto data = rhs.data_for_copy()) + { + shared_data_.assign(HPX_MOVE(data)); + } + else + { + shared_data_.reset(); + } + } + + // a copy that never creates the worker threads of the original + enum class no_init_t : std::uint8_t + { + no_init + }; + static constexpr no_init_t no_init = no_init_t::no_init; + + suspending_fork_join_executor( + suspending_fork_join_executor const& rhs, no_init_t) noexcept + : shared_data_(rhs.shared_data_) + , pu_mask_(rhs.pu_mask_) + , annotation_(rhs.annotation_) + , spin_duration_(rhs.spin_duration_) + , priority_(rhs.priority_) + , stacksize_(rhs.stacksize_) + , schedule_(rhs.schedule_) + , shared_(rhs.shared_) + { + } + + // Created on first use (see data()), so that the executor can be + // constexpr default constructed and destructed. + mutable detail::lazy_shared_ptr shared_data_; + + // The PUs to use, all PUs of the pool if empty. + detail::lazy_shared_ptr pu_mask_; + + char const* annotation_ = nullptr; + std::chrono::nanoseconds spin_duration_ = default_spin_duration; + threads::thread_priority priority_ = threads::thread_priority::bound; + threads::thread_stacksize stacksize_ = + threads::thread_stacksize::small_; + loop_schedule schedule_ = loop_schedule::dynamic; + + // a shared executor, see shared_suspending_fork_join_executor + bool shared_ = false; + }; + + /// \brief A suspending_fork_join_executor that can be used from any + /// number of threads at the same time, and from inside its own + /// parallel regions. + /// + /// All shared_suspending_fork_join_executors with the same configuration + /// (priority, stacksize, loop schedule and spin duration) use the same + /// worker threads: one set for each thread pool, created when an HPX + /// thread of the pool uses such an executor first, and stopped when the + /// runtime starts to shut down. A parallel region runs on these worker + /// threads if they are free. If they are not, because they run a region + /// for another thread already, or because the region is started from + /// inside one of their regions (nested parallelism), the region runs + /// through a parallel_executor instead: one task for each worker thread + /// of the pool, each with a contiguous range of the indices. The same + /// happens if the calling thread is not an HPX thread, and after the + /// worker threads were stopped. Exceptions are reported as the executor + /// that runs the region reports them: the first exception from the + /// worker threads, or an hpx::exception_list from the + /// parallel_executor. + /// + /// Copies of the executor never hold worker threads themselves, so it + /// can be a constexpr variable. The executor of hpx::execution::par and + /// hpx::execution::par_unseq is a shared_suspending_fork_join_executor if + /// HPX is configured with + /// HPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT=ON. Mapping a + /// policy with this executor to a task policy (to_task, as in + /// par(task)) gives it a parallel_executor instead: a task policy runs + /// an algorithm asynchronously, which the worker threads of this + /// executor can't do. + /// + /// As for every suspending_fork_join_executor, the calling thread takes + /// part in a region (see suspending_fork_join_executor), and + /// bulk_async_execute and async_invoke run the region before they + /// return a ready future. Single tasks (sync_execute, async_execute, + /// then_execute, post) and continuations (bulk_then_execute) run as a + /// parallel_executor runs them. + HPX_CXX_CORE_EXPORT class shared_suspending_fork_join_executor + : public suspending_fork_join_executor + { + public: + /// \brief Construct a shared_suspending_fork_join_executor with the + /// default configuration. + constexpr shared_suspending_fork_join_executor() noexcept + : shared_suspending_fork_join_executor( + threads::thread_priority::bound) + { + } + + /// \brief Construct a shared_suspending_fork_join_executor. + /// + /// \param priority The priority of the worker threads. + /// \param stacksize The stacksize of the worker threads. It can't be + /// thread_stacksize::nostack, as the worker threads suspend. + /// \param sched The loop schedule of the parallel regions. + /// \param spin_duration The time a waiting thread spins before it + /// suspends. + explicit constexpr shared_suspending_fork_join_executor( + threads::thread_priority priority, + threads::thread_stacksize stacksize = + threads::thread_stacksize::small_, + loop_schedule sched = loop_schedule::dynamic, + std::chrono::nanoseconds spin_duration = + default_spin_duration) noexcept + : suspending_fork_join_executor( + shared_t::shared, priority, stacksize, sched, spin_duration) + { + } + + /// \cond NOINTERNAL + // Single tasks run as a parallel_executor runs them. + template + decltype(auto) sync_execute(F&& f, Ts&&... ts) const + { + return hpx::execution::parallel_executor().sync_execute( + HPX_FORWARD(F, f), HPX_FORWARD(Ts, ts)...); + } + + template + decltype(auto) async_execute(F&& f, Ts&&... ts) const + { + return hpx::execution::parallel_executor().async_execute( + HPX_FORWARD(F, f), HPX_FORWARD(Ts, ts)...); + } + + template + decltype(auto) then_execute( + F&& f, Future&& predecessor, Ts&&... ts) const + { + return hpx::execution::parallel_executor().then_execute( + HPX_FORWARD(F, f), HPX_FORWARD(Future, predecessor), + HPX_FORWARD(Ts, ts)...); + } + + template + void post(F&& f, Ts&&... ts) const + { + hpx::execution::parallel_executor().post( + HPX_FORWARD(F, f), HPX_FORWARD(Ts, ts)...); + } + + // The executor of the task policy that to_task maps a policy with + // this executor to: a parallel_executor. A task policy runs an + // algorithm asynchronously, which the worker threads of this + // executor can't do. + hpx::execution::parallel_executor to_task() const + { + hpx::execution::parallel_executor exec{}; +#if defined(HPX_HAVE_THREAD_DESCRIPTION) + if (char const* annotation = this->query( + hpx::execution::experimental::get_annotation_t{})) + { + return hpx::execution::experimental::with_annotation( + exec, annotation); + } +#endif + return exec; + } + + // The executor of the policy that to_non_par maps a policy with this + // executor to: the one of a parallel_executor. + decltype(auto) to_non_par() const + { + return hpx::execution::parallel_executor().to_non_par(); + } + + // A continuation runs its region once the predecessor is ready. + template + requires(!std::is_integral_v) + decltype(auto) bulk_then_execute( + F&& f, S const& shape, Future&& predecessor, Ts&&... ts) const + { + return hpx::execution::parallel_executor().bulk_then_execute( + HPX_FORWARD(F, f), shape, HPX_FORWARD(Future, predecessor), + HPX_FORWARD(Ts, ts)...); + } + /// \endcond + }; + + /// \cond NOINTERNAL + template <> + struct is_never_blocking_one_way_executor + : std::true_type + { + }; + + template <> + struct is_bulk_one_way_executor + : std::true_type + { + }; + + template <> + struct is_bulk_two_way_executor + : std::true_type + { + }; + + // The shared executor supports single tasks as well. + template <> + struct is_one_way_executor + : std::true_type + { + }; + + template <> + struct is_two_way_executor + : std::true_type + { + }; + + template <> + struct is_never_blocking_one_way_executor< + shared_suspending_fork_join_executor> : std::true_type + { + }; + + template <> + struct is_bulk_one_way_executor + : std::true_type + { + }; + + template <> + struct is_bulk_two_way_executor + : std::true_type + { + }; + /// \endcond +} // namespace hpx::execution::experimental + +#include diff --git a/libs/core/executors/src/suspending_fork_join_executor.cpp b/libs/core/executors/src/suspending_fork_join_executor.cpp new file mode 100644 index 000000000000..9e1d5f58af27 --- /dev/null +++ b/libs/core/executors/src/suspending_fork_join_executor.cpp @@ -0,0 +1,655 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace hpx::execution::experimental { + + namespace { + + // The number of spin rounds per nanosecond, measured once. A round + // is one look at an atomic and one pause, as in the wait loops below. + // The clock is read only here, never while spinning. + double measure_spin_rounds_per_ns() noexcept + { + constexpr std::uint64_t rounds = 4096; + std::atomic word(0); + + double best = (std::numeric_limits::max)(); + for (int repetition = 0; repetition != 5; ++repetition) + { + auto const start = std::chrono::steady_clock::now(); + for (std::uint64_t k = 0; k != rounds; ++k) + { + if (word.load(std::memory_order_acquire) != 0) + break; + HPX_SMT_PAUSE; + } + auto const elapsed = std::chrono::duration( + std::chrono::steady_clock::now() - start) + .count(); + best = (std::min) (best, elapsed); + } + return best > 0 ? static_cast(rounds) / best : 1.0; + } + + std::uint64_t spin_rounds_for(std::chrono::nanoseconds const duration) + { + if (duration.count() <= 0) + return 0; + + static double const rounds_per_ns = measure_spin_rounds_per_ns(); + return static_cast(std::llround( + static_cast(duration.count()) * rounds_per_ns)); + } + + // A suspended thread that is woken up is scheduled on the worker of + // the thread that wakes it, unless it has bound priority. The worker + // threads and the calling thread are woken by threads that are + // about to spin on their own cores, so they keep bound priority + // while suspended: they are then resumed on the worker they ran on. + class bind_while_suspended + { + public: + bind_while_suspended() noexcept + : self_(threads::get_self_id_data()) + { + if (self_ != nullptr) + { + priority_ = self_->get_priority(); + if (priority_ != threads::thread_priority::bound) + { + self_->set_priority(threads::thread_priority::bound); + } + } + } + + bind_while_suspended(bind_while_suspended const&) = delete; + bind_while_suspended(bind_while_suspended&&) = delete; + bind_while_suspended& operator=( + bind_while_suspended const&) = delete; + bind_while_suspended& operator=(bind_while_suspended&&) = delete; + + ~bind_while_suspended() + { + if (self_ != nullptr && + priority_ != threads::thread_priority::bound) + { + self_->set_priority(priority_); + } + } + + private: + threads::thread_data* self_; + threads::thread_priority priority_ = + threads::thread_priority::bound; + }; + + hpx::threads::mask_type full_pu_mask( + threads::thread_pool_base const* pool) + { + auto const& rp = hpx::resource::get_partitioner(); + + hpx::threads::mask_type mask = hpx::threads::mask_type(); + hpx::threads::resize(mask, hpx::threads::hardware_concurrency()); + + std::size_t const offset = pool->get_thread_offset(); + std::size_t const count = pool->get_os_thread_count(); + for (std::size_t i = 0; i != count; ++i) + { + hpx::threads::set(mask, rp.get_pu_num(offset + i)); + } + return mask; + } + } // namespace + + /////////////////////////////////////////////////////////////////////////// + hpx::threads::mask_type suspending_fork_join_executor::default_pu_mask() + { + return full_pu_mask(threads::detail::get_self_or_default_pool()); + } + + /////////////////////////////////////////////////////////////////////////// + suspending_fork_join_executor::shared_data::shared_data( + threads::thread_priority const priority, + threads::thread_stacksize const stacksize, loop_schedule const sched, + std::chrono::nanoseconds const spin_duration, + hpx::threads::mask_type const* pu_mask, char const* annotation) + : pool_(threads::detail::get_self_or_default_pool()) + , priority_(priority) + , stacksize_(stacksize) + , schedule_(sched) + , spin_rounds_(spin_rounds_for(spin_duration)) + , pu_mask_(pu_mask ? *pu_mask : full_pu_mask(pool_)) + , epoch_(0) + , remaining_(0) + { + if (stacksize_ == threads::thread_stacksize::nostack) + { + HPX_THROW_EXCEPTION(hpx::error::bad_parameter, + "suspending_fork_join_executor::shared_data::shared_data", + "the worker threads of a suspending_fork_join_executor " + "suspend, they can't be stackless"); + } + + init_threads(annotation); + } + + void suspending_fork_join_executor::shared_data::init_threads( + char const* annotation) + { + auto const& rp = hpx::resource::get_partitioner(); + + // The slots are the PUs of the pool that are in the PU mask, in the + // order of the pool's worker threads. + std::size_t const offset = pool_->get_thread_offset(); + std::size_t const count = pool_->get_os_thread_count(); + + std::vector slot_workers; + slot_workers.reserve(count); + for (std::size_t i = 0; i != count; ++i) + { + if (hpx::threads::test(pu_mask_, rp.get_pu_num(offset + i))) + { + slot_workers.push_back(i); + } + } + + num_threads_ = slot_workers.size(); + if (num_threads_ == 0 || num_threads_ != hpx::threads::count(pu_mask_)) + { + HPX_THROW_EXCEPTION(hpx::error::bad_parameter, + "suspending_fork_join_executor::shared_data::init_threads", + "the PU mask has to name PUs of the pool only, PU mask: {}, " + "PUs of the pool in the mask: {}", + pu_mask_, num_threads_); + } + + // The calling thread takes part in the regions if it is a worker + // thread of this pool and runs on one of the PUs of the mask. This + // is decided by its PU, not by its worker number. + if (threads::get_self_id_data() != nullptr && + hpx::get_thread_pool_num() == pool_->get_pool_index()) + { + std::size_t const caller_worker = + hpx::get_local_worker_thread_num(); + for (std::size_t slot = 0; slot != num_threads_; ++slot) + { + if (slot_workers[slot] == caller_worker) + { + caller_slot_ = slot; + break; + } + } + } + + num_workers_ = caller_slot_ == static_cast(-1) ? + num_threads_ : + num_threads_ - 1; + + if (schedule_ == loop_schedule::dynamic && num_threads_ > 1) + { + queues_.resize(num_threads_); + } + + // Create a worker thread for every slot but the one of the calling + // thread. + parking_ = std::make_unique[]>( + num_workers_); + alive_.store(num_workers_, std::memory_order_relaxed); + std::size_t position = 0; + for (std::size_t slot = 0; slot != num_threads_; ++slot) + { + if (slot == caller_slot_) + { + continue; + } + + std::size_t const worker = slot_workers[slot]; + threads::thread_init_data data( + threads::make_thread_function_nullary( + [this, slot, position]() noexcept { + worker_main(slot, position); + }), + threads::thread_description(hpx::util::format("{}: thread ({})", + annotation ? annotation : "suspending_fork_join_executor", + rp.get_pu_num(offset + worker))), + priority_, + threads::thread_schedule_hint( + static_cast(worker)), + stacksize_, threads::thread_schedule_state::pending, false, + pool_->get_scheduler()); + + threads::register_work(data, pool_); + ++position; + } + } + + suspending_fork_join_executor::shared_data::~shared_data() + { + stop_workers(); + } + + void suspending_fork_join_executor::shared_data::stop_workers() noexcept + { + if (stopped_.exchange(true, std::memory_order_acq_rel)) + { + return; + } + + // Let a running region finish, and keep new ones from starting: the + // flag stays set. + hpx::util::yield_while( + [&] { + return in_region_.exchange(true, std::memory_order_acquire); + }, + "suspending_fork_join_executor::stop_workers"); + + if (num_workers_ == 0) + { + return; + } + + // The worker threads may be suspended: wake them with a last epoch + // that tells them to exit. + stop_.store(true, std::memory_order_relaxed); + publish_region(); + + // A worker thread leaves its last notification before it exits, so + // the members it uses have to stay alive until it did. Its exit is + // only a short time after it saw the stop request. + hpx::util::yield_while( + [&] { return alive_.load(std::memory_order_acquire) != 0; }, + "suspending_fork_join_executor::stop_workers"); + } + + /////////////////////////////////////////////////////////////////////////// + // The shared data of all executors whose worker threads may still run. + // A single pre-shutdown function of the runtime (see + // hpx::register_pre_shutdown_function) stops them all. + struct suspending_fork_join_executor::shared_data::shutdown_registry + { + // a shared instance, see shared_suspending_fork_join_executor + struct shared_entry + { + threads::thread_pool_base* pool; + threads::thread_priority priority; + threads::thread_stacksize stacksize; + loop_schedule schedule; + std::chrono::nanoseconds spin_duration; + std::shared_ptr data; + }; + + std::mutex mtx; + std::vector> entries; + std::vector shared; + bool registered = false; + + static shutdown_registry& get() + { + static shutdown_registry registry; + return registry; + } + + // register data, with mtx locked + void add(std::weak_ptr data) + { + std::erase_if(entries, [](std::weak_ptr const& entry) { + return entry.expired(); + }); + entries.push_back(HPX_MOVE(data)); + + if (!registered) + { + // throws if it is too late to register a pre-shutdown + // function + registered = threads::detail::register_pre_shutdown( + &shutdown_registry::stop_all); + } + } + + static void stop_all() noexcept + { + std::vector> stopping; + + // released after the worker threads were stopped + std::vector shared_stopping; + { + auto& registry = get(); + std::lock_guard l(registry.mtx); + stopping.swap(registry.entries); + shared_stopping.swap(registry.shared); + + // a later runtime needs its own registration + registry.registered = false; + } + + for (auto const& entry : stopping) + { + if (auto const data = entry.lock()) + { + data->stop_workers(); + } + } + } + }; + + void suspending_fork_join_executor::shared_data::stop_on_shutdown( + std::weak_ptr data) + { + auto& registry = shutdown_registry::get(); + std::lock_guard l(registry.mtx); + registry.add(HPX_MOVE(data)); + } + + std::shared_ptr + suspending_fork_join_executor::shared_instance() const noexcept + { + if (threads::get_self_id_data() == nullptr) + { + return {}; + } + + return hpx::detail::try_catch_exception_ptr( + [&]() -> std::shared_ptr { + auto* pool = threads::detail::get_self_or_default_pool(); + + auto& registry = shared_data::shutdown_registry::get(); + std::lock_guard l(registry.mtx); + for (auto const& entry : registry.shared) + { + if (entry.pool == pool && entry.priority == priority_ && + entry.stacksize == stacksize_ && + entry.schedule == schedule_ && + entry.spin_duration == spin_duration_) + { + return entry.data; + } + } + + // The first use creates the instance. The lock keeps others + // from creating one at the same time. + auto data = std::make_shared(priority_, stacksize_, + schedule_, spin_duration_, nullptr, annotation_); + registry.add(data); + registry.shared.push_back({pool, priority_, stacksize_, + schedule_, spin_duration_, data}); + return data; + }, + [](std::exception_ptr&&) -> std::shared_ptr { + return {}; + }); + } + + void suspending_fork_join_executor::shared_data::store_exception( + std::exception_ptr&& ep) noexcept + { + std::lock_guard l(exception_mtx_); + if (!exception_) + { + exception_ = HPX_MOVE(ep); + } + } + + /////////////////////////////////////////////////////////////////////////// + // Start a region: the worker threads see the new epoch. The suspended + // worker threads are woken in a tree: the calling thread wakes the worker + // threads at positions 0 and 1, and the one at position p wakes those at + // 2p + 2 and 2p + 3 as soon as it sees the new epoch, whether it was + // suspended or not. All of them are woken after a number of steps that is + // logarithmic in the number of worker threads. + void suspending_fork_join_executor::shared_data::publish_region() noexcept + { + epoch_.data_.fetch_add(1, std::memory_order_seq_cst); + wake_workers(0); + } + + // Wake the worker threads at positions first and first + 1, if they are + // suspended. This pairs with wait_for_region: the waking thread has seen + // the new epoch, so either the worker thread sees it as well, or this sees + // it parked. + void suspending_fork_join_executor::shared_data::wake_workers( + std::size_t const first) noexcept + { + for (std::size_t position = first; + position < first + 2 && position < num_workers_; ++position) + { + parking& p = parking_[position].data_; + if (p.parked.load(std::memory_order_seq_cst)) + { + std::unique_lock l(p.mtx); + p.cv.notify_all(HPX_MOVE(l)); + } + } + } + + // Wait until the epoch differs from seen. Returns false if the worker + // thread has to exit. + bool suspending_fork_join_executor::shared_data::wait_for_region( + std::uint64_t const seen, std::size_t const position) noexcept + { + // spin first + for (std::uint64_t k = 0; k != spin_rounds_; ++k) + { + if (epoch_.data_.load(std::memory_order_acquire) != seen) + { + return !stop_.load(std::memory_order_relaxed); + } + HPX_SMT_PAUSE; + } + + // then suspend + bool aborted = false; + { + bind_while_suspended bind; + + parking& p = parking_[position].data_; + std::unique_lock l(p.mtx); + p.parked.store(true, std::memory_order_seq_cst); + while (epoch_.data_.load(std::memory_order_seq_cst) == seen) + { + hpx::error_code ec(hpx::throwmode::lightweight); + if (p.cv.wait(l, + "suspending_fork_join_executor::wait_for_region", + ec) == threads::thread_restart_state::abort || + ec) + { + // the runtime aborts the suspended threads at shutdown + aborted = true; + break; + } + } + p.parked.store(false, std::memory_order_relaxed); + } + + return !aborted && !stop_.load(std::memory_order_relaxed); + } + + // A worker thread has finished its share of the region. The last one + // wakes the calling thread, if it suspended. This pairs with + // wait_for_workers: either the caller sees no remaining worker threads, + // or this sees it parked. + void suspending_fork_join_executor::shared_data::finish_share() noexcept + { + if (remaining_.data_.fetch_sub(1, std::memory_order_seq_cst) == 1 && + caller_parked_.load(std::memory_order_seq_cst)) + { + std::unique_lock l(caller_mtx_); + caller_cv_.notify_all(HPX_MOVE(l)); + } + } + + void suspending_fork_join_executor::shared_data::wait_for_workers() noexcept + { + // spin first + for (std::uint64_t k = 0; k != spin_rounds_; ++k) + { + if (remaining_.data_.load(std::memory_order_acquire) == 0) + { + return; + } + HPX_SMT_PAUSE; + } + + // then suspend + bind_while_suspended bind; + + std::unique_lock l(caller_mtx_); + caller_parked_.store(true, std::memory_order_seq_cst); + while (remaining_.data_.load(std::memory_order_seq_cst) != 0) + { + // The worker threads use data on the stack of this thread, so it + // can't leave before they are done, even if it was interrupted. + hpx::error_code ec(hpx::throwmode::lightweight); + caller_cv_.wait( + l, "suspending_fork_join_executor::wait_for_workers", ec); + } + caller_parked_.store(false, std::memory_order_relaxed); + } + + void suspending_fork_join_executor::shared_data::worker_main( + std::size_t const slot, std::size_t const position) noexcept + { + std::uint64_t seen = 0; + while (true) + { + bool const run = wait_for_region(seen, position); + + // pass the wake-up on, also when stopping + wake_workers(2 * position + 2); + + if (!run) + { + break; + } + + ++seen; + region_function_(region_body_, *this, slot); + finish_share(); + } + + // nothing may touch this object after this + alive_.fetch_sub(1, std::memory_order_release); + } + + /////////////////////////////////////////////////////////////////////////// + void suspending_fork_join_executor::shared_data::execute_region( + region_function_type* f, void* body, std::size_t const size) + { + if (stopped_.load(std::memory_order_relaxed)) + { + HPX_THROW_EXCEPTION(hpx::error::invalid_status, + "suspending_fork_join_executor::execute_region", + "the worker threads of this suspending_fork_join_executor " + "have exited, the runtime is shutting down"); + } + + // protect against nested (or concurrent) use of this executor + // instance + if (in_region_.exchange(true, std::memory_order_acquire)) + { + HPX_THROW_EXCEPTION(hpx::error::bad_request, + "suspending_fork_join_executor::execute_region", + "this instance of suspending_fork_join_executor is used in " + "nested ways"); + } + + run_locked_region(f, body, size); + } + + bool suspending_fork_join_executor::shared_data::try_execute_region( + region_function_type* f, void* body, std::size_t const size) + { + if (stopped_.load(std::memory_order_relaxed) || + in_region_.exchange(true, std::memory_order_acquire)) + { + return false; + } + + run_locked_region(f, body, size); + return true; + } + + // Run a region, in_region_ was set by the caller. + void suspending_fork_join_executor::shared_data::run_locked_region( + region_function_type* f, void* body, std::size_t const size) + { + struct reset_in_region + { + std::atomic& in_region; + ~reset_in_region() + { + in_region.store(false, std::memory_order_release); + } + }; + reset_in_region const on_exit{in_region_}; + + exception_ = std::exception_ptr(); + region_function_ = f; + region_body_ = body; + region_size_ = size; + + // the queues hold 32 bit indices, larger regions are split statically + dynamic_ = !queues_.empty() && + size <= static_cast( + (std::numeric_limits::max)()); + if (dynamic_) + { + for (std::size_t slot = 0; slot != num_threads_; ++slot) + { + queues_[slot].data_.reset( + static_cast((slot * size) / num_threads_), + static_cast( + ((slot + 1) * size) / num_threads_)); + } + } + + if (num_workers_ != 0) + { + remaining_.data_.store(num_workers_, std::memory_order_relaxed); + publish_region(); + } + + if (caller_slot_ != static_cast(-1)) + { + f(body, *this, caller_slot_); + } + + if (num_workers_ != 0) + { + wait_for_workers(); + } + + if (exception_) + { + std::rethrow_exception(std::exchange(exception_, {})); + } + } +} // namespace hpx::execution::experimental diff --git a/libs/core/executors/tests/performance/CMakeLists.txt b/libs/core/executors/tests/performance/CMakeLists.txt index 7978545c25c2..f44e56f1a4bd 100644 --- a/libs/core/executors/tests/performance/CMakeLists.txt +++ b/libs/core/executors/tests/performance/CMakeLists.txt @@ -3,3 +3,28 @@ # SPDX-License-Identifier: BSL-1.0 # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +set(benchmarks fork_join_executors_benchmark) + +# as a test, run only a few short loops +set(fork_join_executors_benchmark_PARAMETERS + THREADS_PER_LOCALITY 4 ARGS --regions=20 --batches=1 --sizes 0 1000 + --gaps-us 10 --other-work-size=1000 +) + +foreach(benchmark ${benchmarks}) + set(sources ${benchmark}.cpp) + + source_group("Source Files" FILES ${sources}) + + add_hpx_executable( + ${benchmark}_test INTERNAL_FLAGS + SOURCES ${sources} + EXCLUDE_FROM_ALL ${${benchmark}_FLAGS} + FOLDER "Benchmarks/Modules/Core/Executors" + ) + + add_hpx_performance_test( + "modules.executors" ${benchmark} ${${benchmark}_PARAMETERS} + ) +endforeach() diff --git a/libs/core/executors/tests/performance/fork_join_executors_benchmark.cpp b/libs/core/executors/tests/performance/fork_join_executors_benchmark.cpp new file mode 100644 index 000000000000..adb18e8713d8 --- /dev/null +++ b/libs/core/executors/tests/performance/fork_join_executors_benchmark.cpp @@ -0,0 +1,250 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// Compares parallel_executor, fork_join_executor, and +// suspending_fork_join_executor: +// +// - region: the time of one bulk_sync_execute with a trivial body, for +// regions that follow each other directly (latency for small sizes, +// throughput for large ones); +// - gap: the same, but the calling thread works alone for a while between +// two regions, so that the waiting worker threads of the fork-join +// executors spin, yield, or suspend; +// - other work: the time of a parallel loop run through a parallel_executor +// while a fork-join executor exists but is idle (its worker threads wait +// for the next region). +// +// All times are the median of --batches batches. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ex = hpx::execution::experimental; + +/////////////////////////////////////////////////////////////////////////////// +struct options +{ + std::size_t regions = 1000; + std::size_t batches = 7; + std::vector sizes; + std::vector gaps_us; + std::size_t other_work_size = 100000; + std::size_t other_work_us = 1; +}; + +// Spin for the given time on the calling thread, standing in for serial work +// between two parallel regions. +void work_for(std::uint64_t const ns) +{ + hpx::chrono::high_resolution_timer const t; + while (t.elapsed_nanoseconds() < static_cast(ns)) + { + } +} + +double median(std::vector v) +{ + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; +} + +void print(std::string const& executor, std::string const& test, + std::size_t const size, std::size_t const gap_us, double const ns) +{ + std::cout << std::left << std::setw(32) << executor << std::setw(12) << test + << std::right << std::setw(10) << size << std::setw(8) << gap_us + << std::setw(14) << std::fixed << std::setprecision(0) << ns + << "\n" + << std::flush; +} + +// The time of one region, in ns, excluding the gap between regions. +template +double time_regions(Executor const& exec, options const& opts, + std::size_t const size, std::size_t const gap_us) +{ + std::vector data(size); + auto body = [&](std::size_t const i) { data[i] += i; }; + hpx::util::counting_shape shape(std::size_t(0), size); + + // the regions themselves take some time, run fewer with a gap + std::size_t const regions = gap_us == 0 ? + opts.regions : + (std::max) (opts.regions / 10, std::size_t(10)); + + // warm up + for (std::size_t r = 0; r != regions / 10 + 1; ++r) + { + hpx::parallel::execution::bulk_sync_execute(exec, body, shape); + } + + std::vector batches; + for (std::size_t b = 0; b != opts.batches; ++b) + { + double elapsed = 0; + for (std::size_t r = 0; r != regions; ++r) + { + if (gap_us != 0) + { + work_for(gap_us * 1000); + } + + hpx::chrono::high_resolution_timer const t; + hpx::parallel::execution::bulk_sync_execute(exec, body, shape); + elapsed += static_cast(t.elapsed_nanoseconds()); + } + batches.push_back(elapsed / static_cast(regions)); + } + return median(batches); +} + +// The time of a parallel loop through a parallel_executor, in ns, while exec +// is idle. +template +double time_other_work(Executor const* exec, options const& opts) +{ + if (exec != nullptr) + { + // make sure the worker threads exist and wait for the next region + hpx::parallel::execution::bulk_sync_execute( + *exec, [](std::size_t) {}, + hpx::util::counting_shape(std::size_t(0), std::size_t(64))); + } + + std::uint64_t const work_ns = opts.other_work_us * 1000; + auto loop = [&] { + hpx::experimental::for_loop(hpx::execution::par, std::size_t(0), + opts.other_work_size, [&](std::size_t) { work_for(work_ns); }); + }; + + loop(); // warm up + + std::vector batches; + for (std::size_t b = 0; b != opts.batches; ++b) + { + hpx::chrono::high_resolution_timer const t; + loop(); + batches.push_back(static_cast(t.elapsed_nanoseconds())); + } + return median(batches); +} + +template +void run_benchmarks( + std::string const& name, Executor const& exec, options const& opts) +{ + for (std::size_t const size : opts.sizes) + { + print(name, "region", size, 0, time_regions(exec, opts, size, 0)); + } + + for (std::size_t const gap_us : opts.gaps_us) + { + for (std::size_t const size : opts.sizes) + { + print(name, "gap", size, gap_us, + time_regions(exec, opts, size, gap_us)); + } + } +} + +/////////////////////////////////////////////////////////////////////////////// +int hpx_main(hpx::program_options::variables_map& vm) +{ + options opts; + opts.regions = vm["regions"].as(); + opts.batches = vm["batches"].as(); + opts.sizes = vm["sizes"].as>(); + opts.gaps_us = vm["gaps-us"].as>(); + opts.other_work_size = vm["other-work-size"].as(); + opts.other_work_us = vm["other-work-us"].as(); + + std::cout << "threads: " << hpx::get_num_worker_threads() + << ", regions: " << opts.regions << ", batches: " << opts.batches + << "\n"; + std::cout << std::left << std::setw(32) << "executor" << std::setw(12) + << "test" << std::right << std::setw(10) << "size" << std::setw(8) + << "gap_us" << std::setw(14) << "ns" << "\n"; + + { + hpx::execution::parallel_executor const exec; + run_benchmarks("parallel_executor", exec, opts); + } + { + ex::fork_join_executor const exec; + run_benchmarks("fork_join_executor", exec, opts); + } + { + ex::suspending_fork_join_executor const exec; + run_benchmarks("suspending_fork_join_executor", exec, opts); + } + + if (opts.other_work_size != 0) + { + print("none", "other_work", opts.other_work_size, 0, + time_other_work(nullptr, opts)); + { + ex::fork_join_executor const exec; + print("fork_join_executor", "other_work", opts.other_work_size, 0, + time_other_work(&exec, opts)); + } + { + ex::suspending_fork_join_executor const exec; + print("suspending_fork_join_executor", "other_work", + opts.other_work_size, 0, time_other_work(&exec, opts)); + } + } + + return hpx::local::finalize(); +} + +int main(int argc, char* argv[]) +{ + using namespace hpx::program_options; + + // clang-format off + options_description desc_commandline( + "Usage: " HPX_APPLICATION_STRING " [options]"); + desc_commandline.add_options() + ("regions", value()->default_value(1000), + "number of parallel regions per batch") + ("batches", value()->default_value(7), + "number of batches (the median is reported)") + ("sizes", value>()->multitoken() + ->default_value(std::vector{0, 64, 10000, 1000000}, + "0 64 10000 1000000"), + "sizes of the parallel regions") + ("gaps-us", value>()->multitoken() + ->default_value(std::vector{10, 100, 1000}, + "10 100 1000"), + "serial work between two regions in microseconds") + ("other-work-size", value()->default_value(100000), + "iterations of the parallel loop run while an executor is idle " + "(0: skip)") + ("other-work-us", value()->default_value(1), + "time of one iteration of that loop in microseconds"); + // clang-format on + + hpx::local::init_params init_args; + init_args.desc_cmdline = desc_commandline; + + return hpx::local::init(hpx_main, argc, argv, init_args); +} diff --git a/libs/core/executors/tests/unit/CMakeLists.txt b/libs/core/executors/tests/unit/CMakeLists.txt index 6360c95bd11d..50b4dda27469 100644 --- a/libs/core/executors/tests/unit/CMakeLists.txt +++ b/libs/core/executors/tests/unit/CMakeLists.txt @@ -31,7 +31,10 @@ set(tests sequenced_executor service_executors shared_parallel_executor + shared_suspending_fork_join_executor standalone_thread_pool_executor + suspending_fork_join_executor + suspending_fork_join_executor_shutdown task_scheduler thread_pool_scheduler ) diff --git a/libs/core/executors/tests/unit/shared_suspending_fork_join_executor.cpp b/libs/core/executors/tests/unit/shared_suspending_fork_join_executor.cpp new file mode 100644 index 000000000000..ab35eaefe71c --- /dev/null +++ b/libs/core/executors/tests/unit/shared_suspending_fork_join_executor.cpp @@ -0,0 +1,294 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// A shared_suspending_fork_join_executor can be used from many threads at the +// same time and from inside its own regions: a region that finds the worker +// threads busy runs through a parallel_executor instead. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using hpx::execution::experimental::shared_suspending_fork_join_executor; + +// the executor can be a constexpr variable +constexpr shared_suspending_fork_join_executor global_exec{}; + +#if defined(HPX_HAVE_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT) +static_assert(std::is_same_v); +static_assert( + std::is_same_v); +#else +static_assert(std::is_same_v); +static_assert( + std::is_same_v); +#endif + +// the task policies always use parallel_executor, also when mapped from a +// policy with a shared_suspending_fork_join_executor +static_assert( + std::is_same_v); +static_assert(std::is_same_v< + hpx::execution::parallel_unsequenced_task_policy::executor_type, + hpx::execution::parallel_executor>); +static_assert( + std::is_same_v())( + hpx::execution::task))>::executor_type, + hpx::execution::parallel_executor>); +static_assert( + std::is_same_v())( + hpx::execution::task))>::executor_type, + hpx::execution::parallel_executor>); + +// all elements are visited exactly once +void test_bulk(shared_suspending_fork_join_executor const& exec) +{ + for (std::size_t const size : {0, 1, 7, 1000, 100000}) + { + std::vector> visited(size); + std::vector indices(size); + std::iota(indices.begin(), indices.end(), std::size_t(0)); + + hpx::parallel::execution::bulk_sync_execute( + exec, [&](std::size_t const i) { ++visited[i]; }, indices); + + for (auto const& v : visited) + { + HPX_TEST_EQ(v.load(), 1); + } + + auto const results = hpx::parallel::execution::bulk_sync_execute( + exec, [](std::size_t const i) { return 2 * i; }, indices); + HPX_TEST_EQ(results.size(), size); + for (std::size_t i = 0; i != results.size(); ++i) + { + HPX_TEST_EQ(results[i], 2 * i); + } + } +} + +// a region started from inside a region falls back to the parallel_executor +void test_nested() +{ + shared_suspending_fork_join_executor const exec; + + constexpr std::size_t outer = 64; + constexpr std::size_t inner = 1000; + + std::vector outer_indices(outer); + std::iota(outer_indices.begin(), outer_indices.end(), std::size_t(0)); + std::vector inner_indices(inner); + std::iota(inner_indices.begin(), inner_indices.end(), std::size_t(0)); + + std::atomic count{0}; + hpx::parallel::execution::bulk_sync_execute( + exec, + [&](std::size_t) { + hpx::parallel::execution::bulk_sync_execute( + exec, [&](std::size_t) { ++count; }, inner_indices); + }, + outer_indices); + + HPX_TEST_EQ(count.load(), outer * inner); +} + +// many threads use the executor at the same time +void test_concurrent() +{ + constexpr std::size_t num_tasks = 32; + constexpr std::size_t num_regions = 100; + constexpr std::size_t size = 1000; + + std::vector indices(size); + std::iota(indices.begin(), indices.end(), std::size_t(0)); + + std::vector> futures; + futures.reserve(num_tasks); + for (std::size_t t = 0; t != num_tasks; ++t) + { + futures.push_back(hpx::async([&]() { + shared_suspending_fork_join_executor const exec; + std::atomic count{0}; + for (std::size_t r = 0; r != num_regions; ++r) + { + hpx::parallel::execution::bulk_sync_execute( + exec, [&](std::size_t) { ++count; }, indices); + } + return count.load(); + })); + } + + for (auto& f : futures) + { + HPX_TEST_EQ(f.get(), num_regions * size); + } +} + +// exceptions reach the caller, from the worker threads and from the fallback +void test_exceptions() +{ + shared_suspending_fork_join_executor const exec; + + std::vector indices(1000); + std::iota(indices.begin(), indices.end(), std::size_t(0)); + + auto const throwing = [](std::size_t const i) { + if (i == 517) + { + throw std::runtime_error("test"); + } + }; + + bool caught = false; + try + { + hpx::parallel::execution::bulk_sync_execute(exec, throwing, indices); + } + catch (hpx::exception_list const&) + { + caught = true; + } + catch (std::runtime_error const&) + { + caught = true; + } + HPX_TEST(caught); + + // nested: the inner region runs through the parallel_executor + std::atomic caught_inner{0}; + std::vector outer(8); + hpx::parallel::execution::bulk_sync_execute( + exec, + [&](std::size_t) { + try + { + hpx::parallel::execution::bulk_sync_execute( + exec, throwing, indices); + } + catch (hpx::exception_list const&) + { + ++caught_inner; + } + catch (std::runtime_error const&) + { + ++caught_inner; + } + }, + outer); + HPX_TEST_EQ(caught_inner.load(), outer.size()); + + // the executor still works + test_bulk(exec); +} + +// the parallel algorithms work with the executor, also nested +void test_algorithms() +{ + shared_suspending_fork_join_executor const exec; + auto const policy = hpx::execution::par.on(exec); + + std::vector v(100000); + std::iota(v.begin(), v.end(), std::uint64_t(0)); + std::uint64_t const expected = (v.size() - 1) * v.size() / 2; + + HPX_TEST_EQ( + hpx::reduce(policy, v.begin(), v.end(), std::uint64_t(0)), expected); + HPX_TEST_EQ(hpx::reduce(policy(hpx::execution::task), v.begin(), v.end(), + std::uint64_t(0)) + .get(), + expected); + HPX_TEST_EQ(hpx::reduce(hpx::execution::par_unseq.on(exec), v.begin(), + v.end(), std::uint64_t(0)), + expected); + + std::vector sums(v.size()); + hpx::inclusive_scan(policy, v.begin(), v.end(), sums.begin()); + HPX_TEST_EQ(sums.back(), expected); + + std::vector reversed(v.rbegin(), v.rend()); + hpx::sort(policy, reversed.begin(), reversed.end()); + HPX_TEST(reversed == v); + + std::atomic nested_sum{0}; + hpx::for_each(policy, v.begin(), v.begin() + 100, [&](std::uint64_t) { + nested_sum += hpx::reduce(policy, v.begin(), v.end(), std::uint64_t(0)); + }); + HPX_TEST_EQ(nested_sum.load(), 100 * expected); + + // the default parallel policies (a shared_suspending_fork_join_executor + // with HPX_WITH_SUSPENDING_FORK_JOIN_EXECUTOR_AS_DEFAULT=ON) + HPX_TEST_EQ( + hpx::reduce(hpx::execution::par, v.begin(), v.end(), std::uint64_t(0)), + expected); + HPX_TEST_EQ(hpx::reduce(hpx::execution::par_unseq, v.begin(), v.end(), + std::uint64_t(0)), + expected); + HPX_TEST_EQ(hpx::reduce(hpx::execution::par(hpx::execution::task), + v.begin(), v.end(), std::uint64_t(0)) + .get(), + expected); +} + +// a thread that is not an HPX thread uses the parallel_executor +void test_external_thread() +{ + std::vector indices(1000); + std::atomic count{0}; + + std::thread t([&]() { + hpx::parallel::execution::bulk_sync_execute( + global_exec, [&](std::size_t) { ++count; }, indices); + }); + t.join(); + + HPX_TEST_EQ(count.load(), indices.size()); +} + +int hpx_main() +{ + test_bulk(global_exec); + test_bulk(shared_suspending_fork_join_executor( + hpx::threads::thread_priority::default_, + hpx::threads::thread_stacksize::small_, + shared_suspending_fork_join_executor::loop_schedule::static_)); + test_nested(); + test_concurrent(); + test_exceptions(); + test_algorithms(); + test_external_thread(); + + return hpx::local::finalize(); +} + +int main(int argc, char* argv[]) +{ + HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv), 0, + "HPX main exited with non-zero status"); + + return hpx::util::report_errors(); +} diff --git a/libs/core/executors/tests/unit/suspending_fork_join_executor.cpp b/libs/core/executors/tests/unit/suspending_fork_join_executor.cpp new file mode 100644 index 000000000000..813d9ef7111b --- /dev/null +++ b/libs/core/executors/tests/unit/suspending_fork_join_executor.cpp @@ -0,0 +1,877 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// The tests of fork_join_executor, run with suspending_fork_join_executor, +// and tests of what is particular to suspending_fork_join_executor (lazy +// initialization, callers outside the executor's PUs). + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using hpx::execution::experimental::suspending_fork_join_executor; + +static std::atomic count1{0}; +static std::atomic count2{0}; +static std::atomic count3{0}; +static std::atomic count4{0}; + +/////////////////////////////////////////////////////////////////////////////// +template +void test_processing_mask(ExecutorArgs&&... args) +{ + std::cerr << "test_processing_mask\n"; + + auto const& rp = hpx::resource::get_partitioner(); + auto const& expected_mask = + rp.get_used_pus_mask(hpx::get_worker_thread_num()); + + suspending_fork_join_executor exec{ + expected_mask, std::forward(args)...}; + auto const pus_mask = + hpx::execution::experimental::get_processing_units_mask(exec); + HPX_TEST(pus_mask == expected_mask); + + auto const cores_mask = hpx::execution::experimental::get_cores_mask(exec); + HPX_TEST(cores_mask == expected_mask); + + auto const expected_pu_count = hpx::threads::count(pus_mask); + HPX_TEST_EQ(expected_pu_count, hpx::threads::count(expected_mask)); + + auto const pu_count = + hpx::execution::experimental::processing_units_count(exec); + HPX_TEST_EQ(pu_count, expected_pu_count); + + auto const first_core = hpx::execution::experimental::get_first_core(exec); + HPX_TEST_EQ(first_core, hpx::threads::find_first(expected_mask)); +} + +/////////////////////////////////////////////////////////////////////////////// +void bulk_test(int, int passed_through) //-V813 +{ + ++count1; + HPX_TEST_EQ(passed_through, 42); +} + +template +void test_bulk_sync(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_sync\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + using hpx::placeholders::_1; + using hpx::placeholders::_2; + + suspending_fork_join_executor exec{std::forward(args)...}; + hpx::parallel::execution::bulk_sync_execute( + exec, hpx::bind(&bulk_test, _1, _2), v, 42); + HPX_TEST_EQ(count1.load(), n); + + hpx::parallel::execution::bulk_sync_execute(exec, &bulk_test, v, 42); + HPX_TEST_EQ(count1.load(), 2 * n); +} + +template +void test_bulk_async(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_async\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + using hpx::placeholders::_1; + using hpx::placeholders::_2; + + suspending_fork_join_executor exec{std::forward(args)...}; + hpx::when_all(hpx::parallel::execution::bulk_async_execute( + exec, hpx::bind(&bulk_test, _1, _2), v, 42)) + .get(); + HPX_TEST_EQ(count1.load(), n); + + hpx::when_all( + hpx::parallel::execution::bulk_async_execute(exec, &bulk_test, v, 42)) + .get(); + HPX_TEST_EQ(count1.load(), 2 * n); +} + +/////////////////////////////////////////////////////////////////////////////// +int bulk_test_with_result(int val, int passed_through) //-V813 +{ + ++count1; + HPX_TEST_EQ(passed_through, 42); + return val; +} + +template +void test_bulk_sync_with_result(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_sync_with_result\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + using hpx::placeholders::_1; + using hpx::placeholders::_2; + + suspending_fork_join_executor exec{std::forward(args)...}; + std::vector const result1 = + hpx::parallel::execution::bulk_sync_execute( + exec, hpx::bind(&bulk_test_with_result, _1, _2), v, 42); + HPX_TEST_EQ(count1.load(), n); + HPX_TEST(result1 == v); + + std::vector const result2 = + hpx::parallel::execution::bulk_sync_execute( + exec, &bulk_test_with_result, v, 42); + HPX_TEST_EQ(count1.load(), 2 * n); + HPX_TEST(result2 == v); +} + +template +void test_bulk_async_with_result(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_async_with_result\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + using hpx::placeholders::_1; + using hpx::placeholders::_2; + + suspending_fork_join_executor exec{std::forward(args)...}; + std::vector const result1 = + hpx::parallel::execution::bulk_async_execute( + exec, hpx::bind(&bulk_test_with_result, _1, _2), v, 42) + .get(); + HPX_TEST_EQ(count1.load(), n); + HPX_TEST(result1 == v); + + std::vector const result2 = + hpx::parallel::execution::bulk_async_execute( + exec, &bulk_test_with_result, v, 42) + .get(); + HPX_TEST_EQ(count1.load(), 2 * n); + HPX_TEST(result2 == v); +} + +/////////////////////////////////////////////////////////////////////////////// +void bulk_test_exception(int, int passed_through) //-V813 +{ + HPX_TEST_EQ(passed_through, 42); + throw std::runtime_error("test"); +} + +template +void test_bulk_sync_exception(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_sync_exception\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + suspending_fork_join_executor exec{std::forward(args)...}; + bool caught_exception = false; + try + { + hpx::parallel::execution::bulk_sync_execute( + exec, &bulk_test_exception, v, 42); + + HPX_TEST(false); + } + catch (std::runtime_error const& /*e*/) + { + caught_exception = true; + } + catch (...) + { + HPX_TEST(false); + } + + HPX_TEST(caught_exception); +} + +template +void test_bulk_async_exception(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_async_exception\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + suspending_fork_join_executor exec{std::forward(args)...}; + bool caught_exception = false; + try + { + auto r = hpx::parallel::execution::bulk_async_execute( + exec, &bulk_test_exception, v, 42); + r.get(); + + HPX_TEST(false); + } + catch (std::runtime_error const& /*e*/) + { + caught_exception = true; + } + catch (...) + { + HPX_TEST(false); + } + + HPX_TEST(caught_exception); +} + +/////////////////////////////////////////////////////////////////////////////// +int bulk_test_exception_with_result(int, int passed_through) //-V813 +{ + HPX_TEST_EQ(passed_through, 42); + throw std::runtime_error("test"); +} + +template +void test_bulk_sync_exception_with_result(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_sync_exception_with_result\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + suspending_fork_join_executor exec{std::forward(args)...}; + bool caught_exception = false; + try + { + [[maybe_unused]] std::vector const result = + hpx::parallel::execution::bulk_sync_execute( + exec, &bulk_test_exception_with_result, v, 42); + + HPX_TEST(false); + } + catch (std::runtime_error const& /*e*/) + { + caught_exception = true; + } + catch (...) + { + HPX_TEST(false); + } + + HPX_TEST(caught_exception); +} + +template +void test_bulk_async_exception_with_result(ExecutorArgs&&... args) +{ + std::cerr << "test_bulk_async_exception_with_result\n"; + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + std::iota(std::begin(v), std::end(v), std::rand()); + + suspending_fork_join_executor exec{std::forward(args)...}; + bool caught_exception = false; + try + { + auto r = hpx::parallel::execution::bulk_async_execute( + exec, &bulk_test_exception_with_result, v, 42); + [[maybe_unused]] std::vector const result = r.get(); + + HPX_TEST(false); + } + catch (std::runtime_error const& /*e*/) + { + caught_exception = true; + } + catch (...) + { + HPX_TEST(false); + } + + HPX_TEST(caught_exception); +} + +/////////////////////////////////////////////////////////////////////////////// +template +void test_invoke_sync_homogeneous(ExecutorArgs&&... args) +{ + std::cerr << "test_invoke_sync_homogeneous\n"; + + auto f1 = [] { ++count1; }; + + suspending_fork_join_executor exec{std::forward(args)...}; + + count1 = 0; + hpx::parallel::execution::sync_invoke(exec, f1); + HPX_TEST_EQ(count1.load(), static_cast(1)); + + count1 = 0; + hpx::parallel::execution::sync_invoke(exec, f1, f1); + HPX_TEST_EQ(count1.load(), static_cast(2)); + + count1 = 0; + hpx::parallel::execution::sync_invoke(exec, f1, f1, f1, f1, f1); + HPX_TEST_EQ(count1.load(), static_cast(5)); + + count1 = 0; + hpx::parallel::execution::sync_invoke( + exec, f1, f1, f1, f1, f1, f1, f1, f1, f1, f1, f1); + HPX_TEST_EQ(count1.load(), static_cast(11)); +} + +template +void test_invoke_sync(ExecutorArgs&&... args) +{ + std::cerr << "test_invoke_sync\n"; + + auto f1 = [] { ++count1; }; + auto f2 = [] { ++count2; }; + auto f3 = [] { ++count3; }; + auto f4 = [] { ++count4; }; + + suspending_fork_join_executor exec{std::forward(args)...}; + + count1 = 0; + hpx::parallel::execution::sync_invoke(exec, f1); + HPX_TEST_EQ(count1.load(), static_cast(1)); + + count1 = 0; + count2 = 0; + hpx::parallel::execution::sync_invoke(exec, f1, f2); + HPX_TEST_EQ(count1.load(), static_cast(1)); + HPX_TEST_EQ(count2.load(), static_cast(1)); + + count1 = 0; + count2 = 0; + count3 = 0; + count4 = 0; + hpx::parallel::execution::sync_invoke(exec, f1, f2, f3, f4, f1); + HPX_TEST_EQ(count1.load(), static_cast(2)); + HPX_TEST_EQ(count2.load(), static_cast(1)); + HPX_TEST_EQ(count3.load(), static_cast(1)); + HPX_TEST_EQ(count4.load(), static_cast(1)); + + count1 = 0; + count2 = 0; + count3 = 0; + count4 = 0; + hpx::parallel::execution::sync_invoke( + exec, f1, f2, f3, f4, f1, f4, f1, f2, f3, f4, f1); + HPX_TEST_EQ(count1.load(), static_cast(4)); + HPX_TEST_EQ(count2.load(), static_cast(2)); + HPX_TEST_EQ(count3.load(), static_cast(2)); + HPX_TEST_EQ(count4.load(), static_cast(3)); +} + +template +void test_invoke_sync_homogeneous_exception(ExecutorArgs&&... args) +{ + std::cerr << "test_invoke_sync_homogeneous_exception\n"; + + auto f1 = [] { throw std::runtime_error("test"); }; + + suspending_fork_join_executor exec{std::forward(args)...}; + + bool caught_exception = false; + try + { + hpx::parallel::execution::sync_invoke(exec, f1, f1, f1); + HPX_TEST(false); + } + catch (std::runtime_error const& /*e*/) + { + caught_exception = true; + } + catch (...) + { + HPX_TEST(false); + } + + HPX_TEST(caught_exception); +} + +template +void test_invoke_sync_exception(ExecutorArgs&&... args) +{ + std::cerr << "test_invoke_sync_exception\n"; + + auto f1 = [] {}; + auto f2 = [] { throw std::runtime_error("test"); }; + + suspending_fork_join_executor exec{std::forward(args)...}; + + bool caught_exception = false; + try + { + hpx::parallel::execution::sync_invoke(exec, f1, f2); + HPX_TEST(false); + } + catch (std::runtime_error const& /*e*/) + { + caught_exception = true; + } + catch (...) + { + HPX_TEST(false); + } + + HPX_TEST(caught_exception); +} + +void static_check_executor() +{ + using namespace hpx::traits; + + static_assert(is_bulk_one_way_executor_v, + "is_bulk_one_way_executor_v"); + static_assert(is_bulk_two_way_executor_v, + "is_bulk_two_way_executor_v"); +} + +void test_executor(hpx::threads::thread_priority priority, + hpx::threads::thread_stacksize stacksize, + suspending_fork_join_executor::loop_schedule schedule, + std::chrono::nanoseconds spin_duration) +{ + std::cerr << "testing suspending_fork_join_executor with priority = " + << priority << ", stacksize = " << stacksize + << ", schedule = " << schedule + << ", spin duration = " << spin_duration.count() << " ns\n"; + + auto const args = + std::make_tuple(priority, stacksize, schedule, spin_duration); + auto run = [&](auto f) { std::apply(f, args); }; + + run([](auto... a) { test_bulk_sync(a...); }); + run([](auto... a) { test_bulk_async(a...); }); + run([](auto... a) { test_bulk_sync_exception(a...); }); + run([](auto... a) { test_bulk_async_exception(a...); }); + + run([](auto... a) { test_bulk_sync_with_result(a...); }); + run([](auto... a) { test_bulk_async_with_result(a...); }); + run([](auto... a) { test_bulk_sync_exception_with_result(a...); }); + run([](auto... a) { test_bulk_async_exception_with_result(a...); }); + + run([](auto... a) { test_invoke_sync_homogeneous(a...); }); + run([](auto... a) { test_invoke_sync(a...); }); + run([](auto... a) { test_invoke_sync_homogeneous_exception(a...); }); + run([](auto... a) { test_invoke_sync_exception(a...); }); + + run([](auto... a) { test_processing_mask(a...); }); +} + +void test_static_large_range() +{ + // Regression test for #6922 + // Strategy- Sums indices straddling UINT32_MAX and compare + // against closed-form expected arithmetic sum. + + suspending_fork_join_executor exec; + + auto const uint32_max = + static_cast((std::numeric_limits::max)()); + + std::size_t const low = uint32_max - 500; + std::size_t const high = uint32_max + 500; + + // sum of integers [lo, hi) = n*(lo + hi - 1)/2 + std::size_t const n = high - low; + std::size_t const expected_sum = n * (low + high - 1) / 2; + + std::atomic sum{0}; + + hpx::for_each(hpx::execution::par.on(exec), + hpx::util::counting_iterator(low), + hpx::util::counting_iterator(high), + [&sum](std::size_t i) { sum.fetch_add(i, std::memory_order_relaxed); }); + + HPX_TEST_EQ(sum.load(), expected_sum); +} + +/////////////////////////////////////////////////////////////////////////////// +void test_get_scheduler() +{ + namespace ex = hpx::execution::experimental; + namespace tt = hpx::this_thread::experimental; + + std::cerr << "test_get_scheduler\n"; + + // Test 1: get_scheduler returns a valid scheduler + suspending_fork_join_executor exec{}; + auto sched = ex::get_scheduler(exec); + + // Test 2: scheduler can be used to schedule work via then + sync_wait + auto result = hpx::get<0>( + *(tt::sync_wait(ex::then(ex::schedule(sched), []() { return 42; })))); + HPX_TEST_EQ(result, 42); + + // Test 3: scheduled work runs on an HPX worker thread + hpx::thread::id scheduled_thread_id{}; + tt::sync_wait(ex::then(ex::schedule(sched), + [&]() { scheduled_thread_id = hpx::this_thread::get_id(); })); + HPX_TEST(scheduled_thread_id != hpx::thread::id{}); +} + +/////////////////////////////////////////////////////////////////////////////// +// The executor is constexpr default constructible, its worker threads are +// created on first use. +static_assert( + std::is_nothrow_default_constructible_v); + +constinit suspending_fork_join_executor global_exec{}; + +void test_lazy_initialization() +{ + std::cerr << "test_lazy_initialization\n"; + + // queries work before the worker threads exist + std::size_t const pu_count = + hpx::execution::experimental::processing_units_count(global_exec); + HPX_TEST_EQ(pu_count, hpx::get_num_worker_threads()); + + count1 = 0; + constexpr std::size_t n = 107; + std::vector v(n); + hpx::parallel::execution::bulk_sync_execute(global_exec, &bulk_test, v, 42); + HPX_TEST_EQ(count1.load(), n); + HPX_TEST_EQ( + hpx::execution::experimental::processing_units_count(global_exec), + pu_count); + + // copies share the worker threads + suspending_fork_join_executor const copy = global_exec; + HPX_TEST(copy == global_exec); + hpx::parallel::execution::bulk_sync_execute(copy, &bulk_test, v, 42); + HPX_TEST_EQ(count1.load(), 2 * n); + + // an executor that is copied into an execution policy before its first + // use creates its worker threads when it is copied + suspending_fork_join_executor fresh{}; + hpx::for_each(hpx::execution::par.on(fresh), v.begin(), v.end(), + [](int) { ++count1; }); + HPX_TEST_EQ(count1.load(), 3 * n); + + // release the worker threads of the global executor while the runtime + // is still running + global_exec = suspending_fork_join_executor{}; +} + +/////////////////////////////////////////////////////////////////////////////// +hpx::threads::mask_type mask_of_workers( + std::size_t const first, std::size_t const last, std::size_t const skip) +{ + auto const& rp = hpx::resource::get_partitioner(); + + hpx::threads::mask_type mask = hpx::threads::mask_type(); + hpx::threads::resize(mask, hpx::threads::hardware_concurrency()); + for (std::size_t i = first; i != last; ++i) + { + if (i != skip) + { + hpx::threads::set(mask, rp.get_pu_num(i)); + } + } + return mask; +} + +// Run regions and check that they don't run anything on the calling thread. +void check_caller_not_participating(suspending_fork_join_executor const& exec, + std::size_t const expected_pu_count) +{ + HPX_TEST_EQ(hpx::execution::experimental::processing_units_count(exec), + expected_pu_count); + + auto const caller = hpx::this_thread::get_id(); + std::atomic on_caller{0}; + std::atomic count{0}; + + constexpr std::size_t n = 107; + std::vector v(n); + for (int i = 0; i != 10; ++i) + { + hpx::parallel::execution::bulk_sync_execute( + exec, + [&](int) { + ++count; + if (hpx::this_thread::get_id() == caller) + ++on_caller; + }, + v); + } + HPX_TEST_EQ(count.load(), 10 * n); + HPX_TEST_EQ(on_caller.load(), static_cast(0)); +} + +// The PU of the calling thread is not in the executor's PU mask. +void test_caller_not_in_mask( + suspending_fork_join_executor::loop_schedule const schedule) +{ + std::cerr << "test_caller_not_in_mask: " << schedule << "\n"; + + std::size_t const num_threads = hpx::get_num_worker_threads(); + if (num_threads < 2) + return; + + suspending_fork_join_executor const exec( + mask_of_workers(0, num_threads, hpx::get_worker_thread_num()), + hpx::threads::thread_priority::bound, + hpx::threads::thread_stacksize::small_, schedule); + + check_caller_not_participating(exec, num_threads - 1); +} + +// The calling thread runs on a worker thread whose number is not smaller +// than the number of PUs of the executor (see #8230). +void test_caller_on_higher_worker( + suspending_fork_join_executor::loop_schedule const schedule) +{ + std::cerr << "test_caller_on_higher_worker: " << schedule << "\n"; + + std::size_t const num_threads = hpx::get_num_worker_threads(); + if (num_threads < 3) + return; + + std::size_t const caller_worker = num_threads - 1; + hpx::execution::parallel_executor const pexec( + hpx::threads::thread_priority::bound, + hpx::threads::thread_stacksize::default_, + hpx::threads::thread_schedule_hint( + static_cast(caller_worker))); + + hpx::async(pexec, [&] { + HPX_TEST_EQ(hpx::get_worker_thread_num(), caller_worker); + + suspending_fork_join_executor const exec( + mask_of_workers(0, 2, static_cast(-1)), + hpx::threads::thread_priority::bound, + hpx::threads::thread_stacksize::small_, schedule); + + check_caller_not_participating(exec, 2); + }).get(); +} + +// The calling thread is not an HPX thread. +void test_external_caller( + suspending_fork_join_executor::loop_schedule const schedule) +{ + std::cerr << "test_external_caller: " << schedule << "\n"; + + std::atomic done{false}; + std::atomic count{0}; + constexpr std::size_t n = 107; + + std::thread t([&] { + { + suspending_fork_join_executor const exec( + hpx::threads::thread_priority::bound, + hpx::threads::thread_stacksize::small_, schedule); + + std::vector v(n); + for (int i = 0; i != 10; ++i) + { + hpx::parallel::execution::bulk_sync_execute( + exec, [&](int) { ++count; }, v); + } + } + + // the executor waits in its destructor for its worker threads + done = true; + }); + + // The core of this thread has a worker thread of the executor as well, + // so this thread must not block it. + while (!done) + { + hpx::this_thread::yield(); + } + t.join(); + + HPX_TEST_EQ(count.load(), 10 * n); +} + +/////////////////////////////////////////////////////////////////////////////// +void test_nested_use() +{ + std::cerr << "test_nested_use\n"; + + suspending_fork_join_executor const exec; + std::atomic caught{0}; + + constexpr std::size_t n = 16; + std::vector v(n); + hpx::parallel::execution::bulk_sync_execute( + exec, + [&](int) { + try + { + hpx::parallel::execution::bulk_sync_execute( + exec, [](int) {}, std::vector(4)); + } + catch (hpx::exception const& e) + { + if (e.get_error() == hpx::error::bad_request) + ++caught; + } + }, + v); + HPX_TEST_EQ(caught.load(), n); + + // the executor can still be used + count1 = 0; + hpx::parallel::execution::bulk_sync_execute(exec, &bulk_test, v, 42); + HPX_TEST_EQ(count1.load(), n); +} + +void test_nostack_rejected() +{ + std::cerr << "test_nostack_rejected\n"; + + suspending_fork_join_executor const exec( + hpx::threads::thread_priority::bound, + hpx::threads::thread_stacksize::nostack); + + bool caught = false; + try + { + hpx::parallel::execution::bulk_sync_execute( + exec, [](int) {}, std::vector(4)); + } + catch (hpx::exception const& e) + { + caught = e.get_error() == hpx::error::bad_parameter; + } + HPX_TEST(caught); +} + +// Work bound to each of the cores runs while the executor is idle. +void test_idle_cores_run_other_work() +{ + std::cerr << "test_idle_cores_run_other_work\n"; + + suspending_fork_join_executor const exec; + std::vector v(64); + hpx::parallel::execution::bulk_sync_execute(exec, [](int) {}, v); + + std::size_t const num_threads = hpx::get_num_worker_threads(); + std::vector> futures; + futures.reserve(num_threads); + for (std::size_t i = 0; i != num_threads; ++i) + { + hpx::execution::parallel_executor const pexec( + hpx::threads::thread_priority::bound, + hpx::threads::thread_stacksize::default_, + hpx::threads::thread_schedule_hint(static_cast(i))); + futures.push_back( + hpx::async(pexec, [] { return hpx::get_worker_thread_num(); })); + } + for (std::size_t i = 0; i != num_threads; ++i) + { + HPX_TEST_EQ(futures[i].get(), i); + } + + // and the executor still works afterwards + count1 = 0; + hpx::parallel::execution::bulk_sync_execute(exec, &bulk_test, v, 42); + HPX_TEST_EQ(count1.load(), v.size()); +} + +/////////////////////////////////////////////////////////////////////////////// +int hpx_main() +{ + static_check_executor(); + + test_lazy_initialization(); + + // P2300 get_scheduler bridge test + test_get_scheduler(); + + test_static_large_range(); + + for (auto const schedule : { + suspending_fork_join_executor::loop_schedule::static_, + suspending_fork_join_executor::loop_schedule::dynamic, + }) + { + test_caller_not_in_mask(schedule); + test_caller_on_higher_worker(schedule); + test_external_caller(schedule); + } + + test_nested_use(); + test_nostack_rejected(); + test_idle_cores_run_other_work(); + + for (auto const priority : { + hpx::threads::thread_priority::low, + hpx::threads::thread_priority::normal, + hpx::threads::thread_priority::high, + hpx::threads::thread_priority::bound, + }) + { + for (auto const schedule : { + suspending_fork_join_executor::loop_schedule::static_, + suspending_fork_join_executor::loop_schedule::dynamic, + }) + { + // a spin duration of zero suspends on every wait + for (auto const spin_duration : { + std::chrono::nanoseconds(0), + suspending_fork_join_executor::default_spin_duration, + }) + { + test_executor(priority, hpx::threads::thread_stacksize::small_, + schedule, spin_duration); + } + } + } + + return hpx::local::finalize(); +} + +int main(int argc, char* argv[]) +{ + // Initialize and run HPX + HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv), 0, + "HPX main exited with non-zero status"); + + return hpx::util::report_errors(); +} diff --git a/libs/core/executors/tests/unit/suspending_fork_join_executor_shutdown.cpp b/libs/core/executors/tests/unit/suspending_fork_join_executor_shutdown.cpp new file mode 100644 index 000000000000..11a81c68265e --- /dev/null +++ b/libs/core/executors/tests/unit/suspending_fork_join_executor_shutdown.cpp @@ -0,0 +1,58 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// The worker threads of a suspending_fork_join_executor suspend while they +// wait for work. A runtime can't stop while it has suspended threads, so the +// worker threads have to exit when the runtime starts to stop, even if the +// executor still exists (here: a global executor). + +#include +#include +#include +#include + +#include +#include +#include + +using hpx::execution::experimental::suspending_fork_join_executor; + +constinit suspending_fork_join_executor global_exec{}; + +std::atomic count{0}; + +int hpx_main() +{ + // creates the worker threads, which then suspend + std::vector v(107); + hpx::parallel::execution::bulk_sync_execute( + global_exec, [](int) { ++count; }, v); + HPX_TEST_EQ(count.load(), v.size()); + + // global_exec still exists, with suspended worker threads + return hpx::local::finalize(); +} + +int main(int argc, char* argv[]) +{ + HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv), 0, + "HPX main exited with non-zero status"); + + // the worker threads have exited, the executor can't be used anymore + bool caught = false; + try + { + hpx::parallel::execution::bulk_sync_execute( + global_exec, [](int) {}, std::vector(4)); + } + catch (hpx::exception const& e) + { + caught = e.get_error() == hpx::error::invalid_status; + } + HPX_TEST(caught); + + return hpx::util::report_errors(); +} diff --git a/libs/core/init_runtime_local/src/init_runtime_local.cpp b/libs/core/init_runtime_local/src/init_runtime_local.cpp index 77875b49905a..aa422d86011b 100644 --- a/libs/core/init_runtime_local/src/init_runtime_local.cpp +++ b/libs/core/init_runtime_local/src/init_runtime_local.cpp @@ -415,6 +415,8 @@ namespace hpx { &hpx::detail::get_default_pool); hpx::threads::detail::set_get_default_timer_service( &hpx::detail::get_default_timer_service); + hpx::threads::detail::set_register_pre_shutdown( + &hpx::register_pre_shutdown_function); hpx::threads::detail::set_get_locality_id(&get_locality_id); hpx::parallel::execution::detail::set_get_pu_mask( &hpx::detail::get_pu_mask); diff --git a/libs/core/runtime_local/src/runtime_local.cpp b/libs/core/runtime_local/src/runtime_local.cpp index b8d34a4c5936..25c8a16516b2 100644 --- a/libs/core/runtime_local/src/runtime_local.cpp +++ b/libs/core/runtime_local/src/runtime_local.cpp @@ -1893,6 +1893,45 @@ namespace hpx { int runtime::finalize(double /*shutdown_timeout*/) { + // Run the pre-shutdown functions and then the shutdown functions (see + // hpx::register_pre_shutdown_function and + // hpx::register_shutdown_function) on this HPX thread, before the + // runtime waits for its threads to finish: they may end threads that + // would otherwise keep it waiting (suspended threads count as busy). + auto call_functions = [this](std::list& fs) { + // functions may register more functions while they run + while (true) + { + std::list functions; + { + std::lock_guard l(mtx_); + functions.swap(fs); + } + if (functions.empty()) + { + break; + } + + for (shutdown_function_type& f : functions) + { + try + { + f(); + } + catch (...) + { + report_error(std::current_exception()); + } + } + } + }; + + set_state(hpx::state::pre_shutdown); + call_functions(pre_shutdown_functions_); + + set_state(hpx::state::shutdown); + call_functions(shutdown_functions_); + notify_finalize(); return 0; } diff --git a/libs/core/runtime_local/tests/unit/CMakeLists.txt b/libs/core/runtime_local/tests/unit/CMakeLists.txt index 8d468774fd75..a96759f4f455 100644 --- a/libs/core/runtime_local/tests/unit/CMakeLists.txt +++ b/libs/core/runtime_local/tests/unit/CMakeLists.txt @@ -4,8 +4,13 @@ # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -set(tests numa_sensitive pool_timer thread_mapper termination_detection - termination_detection_priority +set(tests + numa_sensitive + pool_timer + shutdown_functions + thread_mapper + termination_detection + termination_detection_priority ) set(pool_timer_PARAMETERS THREADS_PER_LOCALITY 4) diff --git a/libs/core/runtime_local/tests/unit/shutdown_functions.cpp b/libs/core/runtime_local/tests/unit/shutdown_functions.cpp new file mode 100644 index 000000000000..82cf324bd9cc --- /dev/null +++ b/libs/core/runtime_local/tests/unit/shutdown_functions.cpp @@ -0,0 +1,54 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// The local runtime runs the pre-shutdown functions and then the shutdown +// functions on an HPX thread during hpx::local::finalize. + +#include +#include +#include +#include + +#include + +std::string calls; +bool on_hpx_thread = true; + +void record(char const* name) +{ + calls += name; + calls += ' '; + on_hpx_thread = on_hpx_thread && hpx::threads::get_self_ptr() != nullptr; +} + +int hpx_main() +{ + hpx::register_shutdown_function([] { record("shutdown"); }); + hpx::register_pre_shutdown_function([] { + record("pre_shutdown"); + + // a pre-shutdown function may still register a shutdown function + hpx::register_shutdown_function([] { record("late_shutdown"); }); + }); + + HPX_TEST(calls.empty()); + return hpx::local::finalize(); +} + +int main(int argc, char* argv[]) +{ + // registered before the runtime exists + hpx::register_pre_shutdown_function([] { record("early_pre_shutdown"); }); + + HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv), 0, + "HPX main exited with non-zero status"); + + HPX_TEST_EQ(calls, + std::string("early_pre_shutdown pre_shutdown shutdown late_shutdown ")); + HPX_TEST(on_hpx_thread); + + return hpx::util::report_errors(); +} diff --git a/libs/core/threading_base/CMakeLists.txt b/libs/core/threading_base/CMakeLists.txt index de271fbe9f1b..774f3940ac60 100644 --- a/libs/core/threading_base/CMakeLists.txt +++ b/libs/core/threading_base/CMakeLists.txt @@ -14,6 +14,7 @@ set(threading_base_headers hpx/threading_base/detail/reset_backtrace.hpp hpx/threading_base/detail/reset_lco_description.hpp hpx/threading_base/detail/get_default_pool.hpp + hpx/threading_base/detail/register_pre_shutdown.hpp hpx/threading_base/detail/get_default_timer_service.hpp hpx/threading_base/detail/idle_callback.hpp hpx/threading_base/detail/switch_status.hpp @@ -88,6 +89,7 @@ set(threading_base_sources get_default_pool.cpp get_default_timer_service.cpp print.cpp + register_pre_shutdown.cpp register_thread.cpp scheduler_base.cpp scheduler_base_tuned.cpp @@ -126,6 +128,7 @@ add_hpx_module( "hpx/threading_base/detail/switch_status.hpp" "hpx/threading_base/detail/get_default_pool.hpp" "hpx/threading_base/detail/get_default_timer_service.hpp" + "hpx/threading_base/detail/register_pre_shutdown.hpp" "hpx/threading_base/detail/reset_backtrace.hpp" "hpx/threading_base/detail/reset_lco_description.hpp" "hpx/threading_base/detail/switch_status.hpp" diff --git a/libs/core/threading_base/include/hpx/threading_base/detail/register_pre_shutdown.hpp b/libs/core/threading_base/include/hpx/threading_base/detail/register_pre_shutdown.hpp new file mode 100644 index 000000000000..151bc7d09cd8 --- /dev/null +++ b/libs/core/threading_base/include/hpx/threading_base/detail/register_pre_shutdown.hpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include +#include + +namespace hpx::threads::detail { + + // Lets modules below the runtime register pre-shutdown functions (see + // hpx::register_pre_shutdown_function). The runtime installs the hook. + HPX_CXX_CORE_EXPORT using register_pre_shutdown_type = + hpx::function)>; + + HPX_CXX_CORE_EXPORT HPX_CORE_EXPORT void set_register_pre_shutdown( + register_pre_shutdown_type f); + + // Register f to be run by an HPX thread when the runtime starts to shut + // down (in hpx::finalize). Returns false if no runtime installed the hook. + // Throws invalid_status if it is too late to register a pre-shutdown + // function. + HPX_CXX_CORE_EXPORT HPX_CORE_EXPORT bool register_pre_shutdown( + hpx::move_only_function f); +} // namespace hpx::threads::detail diff --git a/libs/core/threading_base/src/register_pre_shutdown.cpp b/libs/core/threading_base/src/register_pre_shutdown.cpp new file mode 100644 index 000000000000..0d378903aebd --- /dev/null +++ b/libs/core/threading_base/src/register_pre_shutdown.cpp @@ -0,0 +1,39 @@ +// Copyright (c) 2026 TheHPXProject +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include + +#include + +namespace hpx::threads::detail { + + namespace { + + register_pre_shutdown_type& register_pre_shutdown_hook() + { + static register_pre_shutdown_type hook; + return hook; + } + } // namespace + + void set_register_pre_shutdown(register_pre_shutdown_type f) + { + register_pre_shutdown_hook() = HPX_MOVE(f); + } + + bool register_pre_shutdown(hpx::move_only_function f) + { + auto const& hook = register_pre_shutdown_hook(); + if (hook.empty()) + { + return false; + } + hook(HPX_MOVE(f)); + return true; + } +} // namespace hpx::threads::detail