fw4spl
Pool.hpp
1 /* ***** BEGIN LICENSE BLOCK *****
2  * FW4SPL - Copyright (C) IRCAD, 2015-2018.
3  * Distributed under the terms of the GNU Lesser General Public License (LGPL) as
4  * published by the Free Software Foundation.
5  * ****** END LICENSE BLOCK ****** */
6 
7 #pragma once
8 
9 #include "fwThread/config.hpp"
10 
11 #include <fwCore/base.hpp>
12 
13 #include <condition_variable>
14 #include <functional>
15 #include <future>
16 #include <memory>
17 #include <mutex>
18 #include <queue>
19 #include <stdexcept>
20 #include <thread>
21 #include <vector>
22 
23 namespace fwThread
24 {
25 
32 class FWTHREAD_CLASS_API Pool
33 {
34 public:
35  typedef std::shared_ptr<Pool> sptr;
36 
38  FWTHREAD_API Pool();
40  FWTHREAD_API Pool(size_t);
42  FWTHREAD_API ~Pool();
43 
45  template<class F, class ... Args>
46  auto post(F&& f, Args&& ... args)
47  ->std::shared_future<typename std::result_of<F(Args ...)>::type>;
48 
49 private:
51  std::vector< std::thread > m_workers;
52 
54  std::queue< std::function<void()> > m_tasks;
55 
57  std::mutex m_queueMutex;
58  std::condition_variable m_condition;
59  bool m_stop;
60 };
61 
62 //-----------------------------------------------------------------------------
63 
64 template<class F, class ... Args>
65 auto Pool::post(F&& f, Args&& ... args)
66 ->std::shared_future<typename std::result_of<F(Args ...)>::type>
67 {
68  using return_type = typename std::result_of<F(Args ...)>::type;
69 
70  auto task = std::make_shared< std::packaged_task<return_type()> >(
71  std::bind(std::forward<F>(f), std::forward<Args>(args) ...)
72  );
73 
74  std::shared_future<return_type> res = task->get_future();
75  {
76  std::unique_lock<std::mutex> lock(m_queueMutex);
77 
78  // don't allow enqueueing after stopping the pool
79  if(m_stop)
80  {
81  throw std::runtime_error("enqueue on stopped Pool");
82  }
83 
84  m_tasks.emplace([task]()
85  {
86  (*task)();
87  });
88  }
89  m_condition.notify_one();
90  return res;
91 }
92 
94 FWTHREAD_API Pool& getDefaultPool();
95 
96 //-----------------------------------------------------------------------------
97 
98 } //namespace fwThread
FWTHREAD_API Pool & getDefaultPool()
Get the default pool.
Definition: Pool.cpp:77
auto post(F &&f, Args &&...args) -> std::shared_future< typename std::result_of< F(Args...)>::type >
add new work item to the pool
Definition: Pool.hpp:65
This class creates and manages a pool of threads which process tasks.
Definition: Pool.hpp:32
This namespace fwThread provides few tools to execute asynchronous tasks on different threads...