thread_pool/pool/ThreadPool.cpp
2023-04-13 13:04:52 +08:00

67 lines
1.6 KiB
C++

//
// Created by dongl on 23-4-12.
//
#include "ThreadPool.h"
class event;
class ThreadPool::thread_tasks {
friend ThreadPool;
public:
explicit thread_tasks(ThreadPool *pool) :
pthread_id(pthread_self()), terminate(false), is_working(false), pool(pool), events(TaskQueue<event>()) {}
void operator () () {
while (true) {
// 为线程环境变量加锁, 互访问工作线程的休眠与唤醒
std::unique_lock<std::mutex> lock(pool->m_conditional_mutex);
if (events.size() <= 10 && !pool->m_tasks.empty()) {
size_t num = pool->m_tasks.size() / pool->m_threads.size();
num = num <= 1 ? 1 : num;
bool st = pool->m_tasks.sub_swap(events, num);
if (!st) continue;
}
if (!events.empty()) {
event fun = event(0, std::function<void()>());
bool st = events.eject(fun);
if (st)
fun();
} else {
pool->m_conditional_lock.wait(lock);
}
}
}
private:
pthread_t pthread_id; // 线程id
bool terminate; // 是否需要结束的标志
bool is_working; // 该事件是否在工作
ThreadPool* pool; // 所属线程池
TaskQueue<event> events;// 任务队列
};
ThreadPool::ThreadPool(const int n_threads) :
m_threads(std::vector<std::thread>(n_threads)), m_shutdown(false) {
for (auto & m_thread : m_threads) {
m_thread = std::thread(thread_tasks(this)); // 分配工作线程
}
}