2020-03-28 00:39:22 +00:00
|
|
|
#include "testPch.h"
|
|
|
|
|
#include "ThreadPool.h"
|
|
|
|
|
#include <ctime>
|
|
|
|
|
|
2021-10-30 07:36:22 +00:00
|
|
|
ThreadPool::ThreadPool(unsigned int initial_pool_size) : m_destruct_pool(false), m_threads() {
|
2023-07-26 04:56:50 +00:00
|
|
|
for (unsigned int i = 0; i < initial_pool_size; i++) {
|
|
|
|
|
m_threads.emplace_back([this]() {
|
|
|
|
|
while (true) {
|
|
|
|
|
std::unique_lock<std::mutex> lock(m_mutex);
|
2023-08-15 03:50:14 +00:00
|
|
|
// thread listening for event and acquire lock if event triggered
|
2023-07-26 04:56:50 +00:00
|
|
|
m_cond_var.wait(lock, [this] { return m_destruct_pool || !m_work_queue.empty(); });
|
|
|
|
|
if (!m_work_queue.empty()) {
|
|
|
|
|
auto work = m_work_queue.front();
|
|
|
|
|
m_work_queue.pop();
|
|
|
|
|
lock.unlock();
|
|
|
|
|
work();
|
|
|
|
|
} else {
|
2023-08-15 03:50:14 +00:00
|
|
|
// Work queue is empty but lock acquired
|
|
|
|
|
// This means we are destructing the pool
|
2023-07-26 04:56:50 +00:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
2020-03-28 00:39:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ThreadPool::~ThreadPool() {
|
2023-07-26 04:56:50 +00:00
|
|
|
m_destruct_pool = true;
|
2023-08-15 03:50:14 +00:00
|
|
|
m_cond_var.notify_all(); // notify destruction to threads
|
2023-07-26 04:56:50 +00:00
|
|
|
for (auto& thread : m_threads) {
|
|
|
|
|
thread.join();
|
|
|
|
|
}
|
2020-03-28 00:39:22 +00:00
|
|
|
}
|