From 98f7b9594fa053b7d8dd717be94a73685a6a8b69 Mon Sep 17 00:00:00 2001 From: Justin Davis <124625725+jtd-formlabs@users.noreply.github.com> Date: Tue, 2 Jul 2024 17:50:49 -0400 Subject: [PATCH] enqueue_detach a non-void returning function (#66) * add capability to enqueue_detach a function that does not return void --- include/thread_pool/thread_pool.h | 26 ++++++++++++++++---------- test/source/thread_pool.cpp | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/include/thread_pool/thread_pool.h b/include/thread_pool/thread_pool.h index 3017aa4..8ff6e3e 100644 --- a/include/thread_pool/thread_pool.h +++ b/include/thread_pool/thread_pool.h @@ -187,25 +187,31 @@ namespace dp { } /** - * @brief Enqueue a task to be executed in the thread pool that returns void. + * @brief Enqueue a task to be executed in the thread pool. Any return value of the function + * will be ignored. * @tparam Function An invokable type. * @tparam Args Argument parameter pack for Function * @param func The callable to be executed * @param args Arguments that will be passed to the function. */ template - requires std::invocable && - std::is_same_v> + requires std::invocable void enqueue_detach(Function &&func, Args &&...args) { - enqueue_task( - std::move([f = std::forward(func), - ... largs = std::forward(args)]() mutable -> decltype(auto) { - // suppress exceptions - try { + enqueue_task(std::move([f = std::forward(func), + ... largs = + std::forward(args)]() mutable -> decltype(auto) { + // suppress exceptions + try { + if constexpr (std::is_same_v>) { std::invoke(f, largs...); - } catch (...) { + } else { + // the function returns an argument, but can be ignored + std::ignore = std::invoke(f, largs...); } - })); + } catch (...) { + } + })); } [[nodiscard]] auto size() const { return threads_.size(); } diff --git a/test/source/thread_pool.cpp b/test/source/thread_pool.cpp index 2c008a5..aeb6b0b 100644 --- a/test/source/thread_pool.cpp +++ b/test/source/thread_pool.cpp @@ -56,6 +56,29 @@ TEST_CASE("Support enqueue with void return type") { CHECK_EQ(value, 16); } +TEST_CASE("Support enqueue_detach with void return type") { + auto value = 8; + { + dp::thread_pool pool; + pool.enqueue_detach([](int& x) { x *= 2; }, std::ref(value)); + } + CHECK_EQ(value, 16); +} + +TEST_CASE("Support enqueue_detach with non void return type") { + auto value = 8; + { + dp::thread_pool pool; + pool.enqueue_detach( + [](int& x) { + x *= 2; + return x; + }, + std::ref(value)); + } + CHECK_EQ(value, 16); +} + TEST_CASE("Ensure input params are properly passed") { dp::thread_pool pool(4); constexpr auto total_tasks = 30;