General Utility Library for C++14  2.12
thread_pool.cc

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

#include <iostream>
using namespace gul14;
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.
std::shared_ptr< ThreadPool > make_thread_pool(std::size_t num_threads, std::size_t capacity=ThreadPool::default_capacity)
Create a thread pool with the desired number of threads and the specified capacity for queuing tasks.
Definition: ThreadPool.h:599
bool sleep(const std::chrono::duration< Rep, Period > &duration, const Trigger &trg)
Sleep for at least the given time span, with the option of being woken up from another thread.
Definition: time_util.h:114
Namespace gul14 contains all functions and classes of the General Utility Library.
Definition: doxygen.h:26
Declaration of time related functions for the General Utility Library.