1.source code
2.线程池需要考虑的因素
template <
typename Task = task_func,
template <typename> class SchedulingPolicy = fifo_scheduler,
template <typename> class SizePolicy = static_size,
template <typename> class SizePolicyController = resize_controller,
template <typename> class ShutdownPolicy = wait_for_all_tasks
>
volatile size_t m_worker_count; // 当前线程池中worker数量
volatile size_t m_target_worker_count; // 期望值 线程池中的worker数
volatile size_t m_active_worker_count; // 正在执行task的worker数量
3.核心变量
mutable recursive_mutex m_monitor;
mutable condition m_worker_idle_or_terminated_event; // A worker is idle or was terminated.
mutable condition m_task_or_terminate_workers_event; // Task is available OR total worker count should be reduced.
4.核心方法(注释部分为核心代码)
// worker_thread<pool_type>::create_and_attach(lockedThis->shared_from_this());
bool resize(size_t const worker_count) volatile
// lockedThis->m_worker_idle_or_terminated_event.notify_all();
void worker_destructed(shared_ptr<worker_type> worker) volatile
// self->m_terminate_all_workers = true;
// m_target_worker_count = 0;
// self->m_task_or_terminate_workers_event.notify_all();
void terminate_all_workers(bool const wait) volatile
// while(lockedThis->m_scheduler.empty())
// {
// // decrease number of workers if necessary
// if(m_worker_count > m_target_worker_count)
// {
// return false; // terminate worker
// }
// else
// {
// m_active_worker_count--;
// lockedThis->m_worker_idle_or_terminated_event.notify_all();
// lockedThis->m_task_or_terminate_workers_event.wait(lock);
// m_active_worker_count++;
// }
// }
bool execute_task() volatile
5.核心类
pool_core
thread_worker