Enhance the threadpool implementation. (#10531)
- Accept an initialization function. - Support void return tasks.
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
* Copyright 2024, XGBoost Contributors
|
||||
*/
|
||||
#include <gtest/gtest.h>
|
||||
#include <xgboost/global_config.h> // for GlobalConfigThreadLocalStore
|
||||
|
||||
#include <cstddef> // for size_t
|
||||
#include <cstdint> // for int32_t
|
||||
@@ -13,7 +14,23 @@
|
||||
namespace xgboost::common {
|
||||
TEST(ThreadPool, Basic) {
|
||||
std::int32_t n_threads = std::thread::hardware_concurrency();
|
||||
ThreadPool pool{n_threads};
|
||||
|
||||
// Set verbosity to 0 for thread-local variable.
|
||||
auto orig = GlobalConfigThreadLocalStore::Get()->verbosity;
|
||||
GlobalConfigThreadLocalStore::Get()->verbosity = 4;
|
||||
// 4 is an invalid value, it's only possible to set it by bypassing the parameter
|
||||
// validation.
|
||||
ASSERT_NE(orig, GlobalConfigThreadLocalStore::Get()->verbosity);
|
||||
ThreadPool pool{n_threads, [config = *GlobalConfigThreadLocalStore::Get()] {
|
||||
*GlobalConfigThreadLocalStore::Get() = config;
|
||||
}};
|
||||
GlobalConfigThreadLocalStore::Get()->verbosity = orig; // restore
|
||||
|
||||
{
|
||||
auto fut = pool.Submit([] { return GlobalConfigThreadLocalStore::Get()->verbosity; });
|
||||
ASSERT_EQ(fut.get(), 4);
|
||||
ASSERT_EQ(GlobalConfigThreadLocalStore::Get()->verbosity, orig);
|
||||
}
|
||||
{
|
||||
auto fut = pool.Submit([] { return 3; });
|
||||
ASSERT_EQ(fut.get(), 3);
|
||||
@@ -45,5 +62,12 @@ TEST(ThreadPool, Basic) {
|
||||
ASSERT_EQ(futures[i].get(), i);
|
||||
}
|
||||
}
|
||||
{
|
||||
std::int32_t val{0};
|
||||
auto fut = pool.Submit([&] { val = 3; });
|
||||
static_assert(std::is_void_v<decltype(fut.get())>);
|
||||
fut.get();
|
||||
ASSERT_EQ(val, 3);
|
||||
}
|
||||
}
|
||||
} // namespace xgboost::common
|
||||
|
||||
Reference in New Issue
Block a user