Skip to content

Commit 951db75

Browse files
committed
Removed Worker class in favor of a lambda capturing this
1 parent 5a8ca17 commit 951db75

File tree

1 file changed

+17
-28
lines changed

1 file changed

+17
-28
lines changed

ThreadPool.h

Lines changed: 17 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,6 @@
1212
#include <stdexcept>
1313

1414
class 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
2617
class ThreadPool {
@@ -31,8 +22,6 @@ class ThreadPool {
3122
-> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>;
3223
~ThreadPool();
3324
private:
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
6437
ThreadPool::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

Comments
 (0)