Skip to content

Commit

Permalink
enqueue_detach a non-void returning function (#66)
Browse files Browse the repository at this point in the history
* add capability to enqueue_detach a function that does not return void
  • Loading branch information
jtd-formlabs authored Jul 2, 2024
1 parent f5549bb commit 98f7b95
Showing 2 changed files with 39 additions and 10 deletions.
26 changes: 16 additions & 10 deletions include/thread_pool/thread_pool.h
Original file line number Diff line number Diff line change
@@ -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 <typename Function, typename... Args>
requires std::invocable<Function, Args...> &&
std::is_same_v<void, std::invoke_result_t<Function &&, Args &&...>>
requires std::invocable<Function, Args...>
void enqueue_detach(Function &&func, Args &&...args) {
enqueue_task(
std::move([f = std::forward<Function>(func),
... largs = std::forward<Args>(args)]() mutable -> decltype(auto) {
// suppress exceptions
try {
enqueue_task(std::move([f = std::forward<Function>(func),
... largs =
std::forward<Args>(args)]() mutable -> decltype(auto) {
// suppress exceptions
try {
if constexpr (std::is_same_v<void,
std::invoke_result_t<Function &&, Args &&...>>) {
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(); }
23 changes: 23 additions & 0 deletions test/source/thread_pool.cpp
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 98f7b95

Please sign in to comment.