progschj / ThreadPool

A simple C++11 Thread Pool implementation
zlib License
7.64k stars 2.21k forks source link

Flexible size thread pool #35

Closed loveyacper closed 4 years ago

loveyacper commented 8 years ago

Thread is created on demand, not when enter main function, and a monitor thread will recycle redundant idle threads.

I modified the worker thread routine, use a thread local working flag to stop worker thread. The working flag is like this:

static thread_local bool working;

If monitor thread detects redundant idle thread, it will enqueue a task item like this:

tasks.emplace([this]() { working = false; });

Then a idle thread will take it , and stop its loop.

loveyacper commented 8 years ago

"Thread is created on demand" means, when enqueue a task item, if there is no idle thread, a thread will be created to fetch this task item; The variable maxIdle indicates thread pool size, default to std::thread::hardware_concurrency(). When threads are busy working, thread pool size may be bigger than maxIdle, and after working, monitor thread will recycle the redundant threads, but pool size will never be smaller than maxIdle.