General Utility Library for C++17 25.4.1
thread_pool.cc

An example on how to use the ThreadPool class to schedule tasks.

An example on how to use the ThreadPool class to schedule tasks.

#include <iostream>
using namespace gul17;
using std::cout;
using namespace std::literals;
int main()
{
// Create a pool with 2 threads (returns a shared_ptr<ThreadPool>)
auto pool = make_thread_pool(2);
pool->add_task([]() { cout << "Task 1\n"; });
pool->add_task([]() { sleep(1); std::cout << "Task 2\n"; });
// Tasks can be scheduled to start later:
// This one should start 2 seconds after enqueueing (if a thread is available)
pool->add_task([]() { cout << "Task 3\n"; }, 2s);
// Probable output:
// Task 1
// Task 2
// Task 3
// Tasks can return results
auto task = pool->add_task([]() { return 42; });
while (not task.is_complete())
sleep(0.1);
// get_result() blocks until the task is complete
cout << "Task result: " << task.get_result() << "\n";
// Tasks can also interact with the pool themselves, e.g. to schedule a continuation:
pool->add_task(
[](ThreadPool& pool) {
cout << "Task 4\n";
pool.add_task([]() { cout << "Task 5, a second later\n"; }, 1s);
});
return 0;
}
Declaration of the ThreadPool class.
A pool of worker threads with a task queue.
Definition ThreadPool.h:111
TaskHandle< std::invoke_result_t< Function, ThreadPool & > > add_task(Function fct, TimePoint start_time={}, std::string name={})
Enqueue a task.
Definition ThreadPool.h:309
Namespace gul17 contains all functions and classes of the General Utility Library.
Definition doxygen.h:26
Declaration of time related functions for the General Utility Library.