Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "threadpool.h"
- namespace dwt {
- threadpool::threadpool(unsigned threads)
- : ready_(false), done_(false), joined_(false),
- tasks_(), threads_(), tasks_mtx_(), go_()
- {
- for (unsigned i = 0; i < threads; ++i)
- threads_.emplace_back(std::bind(&worker_thread_, this));
- }
- threadpool::~threadpool()
- {
- if (!joined_)
- join_all();
- }
- void threadpool::done()
- {
- std::unique_lock<std::mutex> lock(tasks_mtx_);
- done_ = true;
- }
- void threadpool::join_all()
- {
- if (!done_)
- done();
- for (auto& t: threads_)
- t.join();
- joined_ = true;
- }
- void threadpool::worker_thread_()
- {
- // wait for kickoff, if it hasn't happened yet
- {
- std::unique_lock<std::mutex> lock(tasks_mtx_);
- if (!ready_)
- go_.wait(lock);
- }
- std::packaged_task<void()> current_task;
- while (true) {
- {
- std::unique_lock<std::mutex> lock(tasks_mtx_);
- if (!tasks_.empty()) {
- current_task = std::move(tasks_.front());
- tasks_.pop();
- } else /* tasks_ is empty */ if (done_) {
- break;
- } else /* empty, but not done: try again */ {
- continue;
- }
- }
- current_task();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement