58 lines
1.3 KiB
C++
58 lines
1.3 KiB
C++
|
|
#include "thread_pool.hpp"
|
||
|
|
|
||
|
|
ThreadPool::ThreadPool(size_t num_threads) {
|
||
|
|
states = new bool[num_threads]({ false });
|
||
|
|
for (auto i = 0; i < num_threads; ++i) {
|
||
|
|
threads.emplace_back([this, i] {
|
||
|
|
while (true) {
|
||
|
|
std::function<void()> task;
|
||
|
|
|
||
|
|
std::unique_lock<std::mutex> lock(mutex);
|
||
|
|
|
||
|
|
cv.wait(lock, [this] { return !tasks.empty() || stop; });
|
||
|
|
|
||
|
|
if (tasks.empty() || stop) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
states[i] = true;
|
||
|
|
|
||
|
|
task = std::move(tasks.front());
|
||
|
|
tasks.pop();
|
||
|
|
|
||
|
|
lock.unlock();
|
||
|
|
task();
|
||
|
|
|
||
|
|
states[i] = false;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
ThreadPool::~ThreadPool() {
|
||
|
|
std::unique_lock<std::mutex> lock(mutex);
|
||
|
|
stop = true;
|
||
|
|
lock.unlock();
|
||
|
|
|
||
|
|
cv.notify_all();
|
||
|
|
for (auto& thread : threads) {
|
||
|
|
thread.join();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
void ThreadPool::add(std::function<void()> task) {
|
||
|
|
std::unique_lock<std::mutex> lock(mutex);
|
||
|
|
tasks.emplace(std::move(task));
|
||
|
|
cv.notify_one();
|
||
|
|
lock.unlock();
|
||
|
|
}
|
||
|
|
|
||
|
|
uint32_t ThreadPool::size() { return tasks.size(); }
|
||
|
|
bool ThreadPool::isWorking() {
|
||
|
|
for (auto i = 0; i < threads.size(); i++) {
|
||
|
|
if (states[i]) {
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false;
|
||
|
|
}
|