123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- #include <task_queue.hpp>
- #include <iostream>
- int num_threads = std::thread::hardware_concurrency();
- TaskQueue::TaskQueue() {}
- TaskQueue::~TaskQueue() { detachThreads(); }
- void TaskQueue::pushToQueue(std::function<void()> fn) {
- std::unique_lock<std::mutex> lock(m_mutex_lock);
- m_task_queue.push(fn);
- lock.unlock();
- pool_condition.notify_one();
- }
- void TaskQueue::workerLoop() {
- std::function<void()> fn;
- for (;;) {
- {
- std::unique_lock<std::mutex> lock(m_mutex_lock);
- pool_condition
- .wait(
- lock,
- [this]() { return !accepting_tasks || !m_task_queue.empty(); });
- std::cout << "Wait condition met" << std::endl;
- if (!accepting_tasks && m_task_queue.empty()) {
-
- accepting_tasks = true;
- continue;
- }
- std::cout << "Taking task" << std::endl;
- fn = m_task_queue.front();
- m_task_queue.pop();
- accepting_tasks = true;
- }
- fn();
- }
- }
- void TaskQueue::deployWorkers() {
- for (int i = 0; i < (num_threads - 1); i++) {
- m_thread_pool.push_back(std::thread([this]() { workerLoop(); }));
- }
-
- std::unique_lock<std::mutex> lock(m_mutex_lock);
- accepting_tasks = false;
- lock.unlock();
-
-
- pool_condition.notify_all();
- }
- void TaskQueue::initialize() { deployWorkers(); }
- void TaskQueue::detachThreads() {
- for (std::thread& t : m_thread_pool) {
- if (t.joinable()) {
- t.detach();
- }
- }
- }
|