Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <thread_pool.hpp>
- concurrency::thread_pool::thread_pool(int k) {
- workers_count = k;
- stop = false;
- start_workers();
- }
- concurrency::thread_pool::~thread_pool() {
- {
- uniqueLock ul(mutex);
- stop = true;
- }
- cond.notify_all();
- for (int i = 0; i < workers_count; i++) {
- workers[i].join();
- }
- }
- void concurrency::thread_pool::start_workers() {
- for (int i = 0; i < workers_count; i++) {
- //std::thread* t = new std::thread(concurrency::worker(*this));
- //workers.push_back(t);
- workers.emplace_back([this]{
- try {
- while (true) {
- std::function<void()> task(this->pop());
- task();
- }
- } catch (int n) {
- // worker should quit
- }
- });
- }
- }
- template<class F, class ...Args>
- void concurrency::thread_pool::push(F&& f, Args&&... args) {
- if (stop) {
- throw std::runtime_error("push on stopped thread_pool");
- }
- std::function<void()> func = std::bind(f, args...);
- lockGuard l(mutex);
- bool should_wake = queue.empty();
- queue.push(func);
- if (should_wake) {
- cond.notify_one();
- }
- }
- std::function<void()> concurrency::thread_pool::pop() {
- uniqueLock u(mutex);
- while (!stop && queue.size() == 0) {
- cond.wait(u);
- }
- if (stop && queue.size() == 0) {
- throw 1;
- }
- std::function<void()> elm = queue.front();
- queue.pop();
- return elm;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement