Skip to content

Commit

Permalink
add capability to enqueue_detach a function that does not return void.
Browse files Browse the repository at this point in the history
  • Loading branch information
jtd-formlabs committed Jul 2, 2024
1 parent 244afa9 commit fdd50a5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
12 changes: 8 additions & 4 deletions include/thread_pool/thread_pool.h
Original file line number Diff line number Diff line change
Expand Up @@ -187,22 +187,26 @@ 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 {
std::invoke(f, largs...);
if constexpr (std::is_same_v<void, std::invoke_result_t<Function &&, Args &&...>>) {
std::invoke(f, largs...);
} else {
// the function returns an argument, but can be ignored
std::ignore = std::invoke(f, largs...);
}
} catch (...) {
}
}));
Expand Down
23 changes: 23 additions & 0 deletions test/source/thread_pool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit fdd50a5

Please sign in to comment.