mirror of
https://github.com/allankoechke/ThreadPool.git
synced 2026-12-04 01:19:04 +00:00
Pass task by universal reference and variadics
As suggested by daniel-j-h tasks are now taken by universal reference and forwarded with std::forward. Also enqueue takes a variadic argument list and binds the arguments to the task.
This commit is contained in:
14
ThreadPool.h
14
ThreadPool.h
@@ -26,8 +26,8 @@ private:
|
||||
class ThreadPool {
|
||||
public:
|
||||
ThreadPool(size_t);
|
||||
template<class T, class F>
|
||||
std::future<T> enqueue(F f);
|
||||
template<class F, class... Args>
|
||||
auto enqueue(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>;
|
||||
~ThreadPool();
|
||||
private:
|
||||
friend class Worker;
|
||||
@@ -68,15 +68,17 @@ ThreadPool::ThreadPool(size_t threads)
|
||||
}
|
||||
|
||||
// add new work item to the pool
|
||||
template<class T, class F>
|
||||
std::future<T> ThreadPool::enqueue(F f)
|
||||
template<class F, class... Args>
|
||||
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>
|
||||
{
|
||||
typedef decltype(std::forward<F>(f)(std::forward<Args>(args)...)) return_type;
|
||||
|
||||
// don't allow enqueueing after stopping the pool
|
||||
if(stop)
|
||||
throw std::runtime_error("enqueue on stopped ThreadPool");
|
||||
|
||||
auto task = std::make_shared< std::packaged_task<T()> >(f);
|
||||
std::future<T> res = task->get_future();
|
||||
auto task = std::make_shared< std::packaged_task<return_type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
|
||||
std::future<return_type> res = task->get_future();
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queue_mutex);
|
||||
tasks.push([task](){ (*task)(); });
|
||||
|
||||
@@ -12,7 +12,7 @@ int main()
|
||||
|
||||
for(int i = 0; i < 8; ++i) {
|
||||
results.push_back(
|
||||
pool.enqueue<int>([i] {
|
||||
pool.enqueue([i] {
|
||||
std::cout << "hello " << i << std::endl;
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
std::cout << "world " << i << std::endl;
|
||||
|
||||
Reference in New Issue
Block a user