1212#include  < stdexcept> 
1313
1414class  ThreadPool ;
15-  
16- //  our worker thread objects
17- class  Worker  {
18- public: 
19-     Worker (ThreadPool &s) : pool(s) { }
20-     void  operator ()();
21- private: 
22-     ThreadPool &pool;
23- };
2415
2516//  the actual thread pool
2617class  ThreadPool  {
@@ -31,8 +22,6 @@ class ThreadPool {
3122        -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>;
3223    ~ThreadPool ();
3324private: 
34-     friend  class  Worker ;
35- 
3625    //  need to keep track of threads so we can join them
3726    std::vector< std::thread > workers;
3827    //  the task queue
@@ -44,28 +33,28 @@ class ThreadPool {
4433    bool  stop;
4534};
4635
47- void  Worker::operator ()()
48- {
49-     while (true )
50-     {
51-         std::unique_lock<std::mutex> lock (pool.queue_mutex );
52-         while (!pool.stop  && pool.tasks .empty ())
53-             pool.condition .wait (lock);
54-         if (pool.stop  && pool.tasks .empty ())
55-             return ;
56-         std::function<void ()> task (pool.tasks .front ());
57-         pool.tasks .pop ();
58-         lock.unlock ();
59-         task ();
60-     }
61- }
62-  
6336//  the constructor just launches some amount of workers
6437ThreadPool::ThreadPool (size_t  threads)
6538    :   stop(false )
6639{
6740    for (size_t  i = 0 ;i<threads;++i)
68-         workers.push_back (std::thread (Worker (*this )));
41+         workers.push_back (std::thread (
42+             [this ]
43+             {
44+                 while (true )
45+                 {
46+                     std::unique_lock<std::mutex> lock (this ->queue_mutex );
47+                     while (!this ->stop  && this ->tasks .empty ())
48+                         this ->condition .wait (lock);
49+                     if (this ->stop  && this ->tasks .empty ())
50+                         return ;
51+                     std::function<void ()> task (this ->tasks .front ());
52+                     this ->tasks .pop ();
53+                     lock.unlock ();
54+                     task ();
55+                 }
56+             }
57+         ));
6958}
7059
7160//  add new work item to the pool
0 commit comments