36#include <boost/asio.hpp>
37#include <boost/thread.hpp>
49 boost::asio::io_service::work
work;
57 impl(new
Impl(pool_size, queueTasks))
59 for (std::size_t i = 0; i < pool_size; ++i)
61 impl->threads.create_thread(
62 boost::bind(&boost::asio::io_service::run, &impl->io_service));
69 impl->io_service.stop();
74 impl->threads.join_all();
76 catch (
const std::exception&)
84 std::unique_lock lock(impl->mutex);
87 if (!impl->queueTasks && impl->available == 0)
93 if (!impl->queueTasks)
97 auto promise = std::make_shared<std::promise<void>>();
99 impl->io_service.post(
100 [
this, task, promise]
103 promise->set_value();
105 return Handle{promise->get_future()};
111 std::unique_lock lock(impl->mutex);
112 if (!impl->queueTasks)
114 return impl->available;
123 ThreadPool::wrap_task(std::function<
void()> task)
131 catch (
const std::exception&)
133 std::unique_lock lock(impl->mutex);
135 if (!impl->queueTasks)
143 std::unique_lock lock(impl->mutex);
144 if (!impl->queueTasks)
155 mutex(new
std::mutex), functionFinished(functionFinished)
161 if (!joined &&
isValid() && !detached)
163 throw LocalException()
164 <<
"You did not join the thread pool handle before the handle was deleted!";
171 return functionFinished.valid();
178 std::lock_guard<
decltype(*mutex)> lock(*mutex);
186 throw LocalException() <<
"You cannot join a detached thread!";
188 functionFinished.get();
196 std::lock_guard<
decltype(*mutex)> lock(*mutex);
204 throw LocalException() <<
"You cannot detach a joined thread!";
209 const std::shared_future<void>&
212 return functionFinished;
const std::shared_future< void > & getFuture() const
~Handle() noexcept(false)
Handle runTask(std::function< void()> task)
Adds a task to the thread pool if a thread is currently available.
ThreadPool(std::size_t pool_size, bool queueTasks=false)
Constructor.
int getAvailableTaskCount() const
If queing is disabled, returns the number of available threads.
#define ARMARX_CHECK_EXPRESSION(expression)
This macro evaluates the expression and if it turns out to be false it will throw an ExpressionExcept...
This file offers overloads of toIce() and fromIce() functions for STL container types.
boost::asio::io_service::work work
boost::thread_group threads
Impl(std::size_t pool_size, bool queueTasks)
boost::asio::io_service io_service