Skip to content

Commit 0b4215e

Browse files
committed
threadpool: submitMany
1 parent f5eca8d commit 0b4215e

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/test/threadpool_tests.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,24 @@ BOOST_AUTO_TEST_CASE(threadpool_basic)
263263
// Pool should be stopped and no workers remaining
264264
BOOST_CHECK_EQUAL(threadPool.WorkersCount(), 0);
265265
}
266+
267+
// Testing multi-task submission.
268+
// Note: Tasks can even return different types!
269+
{
270+
ThreadPool threadPool(POOL_NAME);
271+
threadPool.Start(NUM_WORKERS_DEFAULT);
272+
273+
const auto futures = threadPool.SubmitMany(
274+
[]() { std::cout << "Hi" << std::endl; },
275+
[]() { std::cout << "Andrew" << std::endl; },
276+
[]() { return 1; },
277+
[]() { return "different return type"; }
278+
);
279+
280+
for (auto& fut : futures) {
281+
fut.wait();
282+
}
283+
}
266284
}
267285

268286
BOOST_AUTO_TEST_SUITE_END()

src/util/threadpool.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,31 @@ class ThreadPool {
161161
return future;
162162
}
163163

164+
template<class... Fs> EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
165+
auto SubmitMany(Fs&&... fns)
166+
{
167+
std::vector<std::future<void>> futures;
168+
futures.reserve(sizeof...(Fs));
169+
170+
{
171+
LOCK(m_mutex);
172+
if (m_interrupt || m_workers.empty()) {
173+
throw std::runtime_error("No active workers; cannot accept new tasks");
174+
}
175+
176+
auto enqueue = [&](auto&& fn) EXCLUSIVE_LOCKS_REQUIRED(m_mutex) {
177+
std::packaged_task<void()> task{std::forward<decltype(fn)>(fn)};
178+
futures.emplace_back(task.get_future());
179+
m_work_queue.emplace(std::move(task));
180+
};
181+
182+
(enqueue(std::forward<Fs>(fns)), ...);
183+
}
184+
185+
m_cv.notify_all();
186+
return futures;
187+
}
188+
164189
/**
165190
* @brief Execute a single queued task synchronously.
166191
* Removes one task from the queue and executes it on the calling thread.

0 commit comments

Comments
 (0)