Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enqueue_detach a non-void returning function #66

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading