Thread Pooling in C 11
Issue: Creating and deleting threads repeatedly is expensive. How can we establish a persistent thread pool to handle tasks without incurring this overhead?
Solution:
Implementing the ThreadPool Class
To create an efficient thread pool, we first define the ThreadPool class:
class ThreadPool { public: void Start(); void QueueJob(const std::function<void()>& job); void Stop(); bool busy(); private: void ThreadLoop(); bool should_terminate = false; std::mutex queue_mutex; std::condition_variable mutex_condition; std::vector<std::thread> threads; std::queue<std::function<void()>> jobs; };
1. ThreadPool::Start:
Creates a fixed number of threads based on system capabilities:
void ThreadPool::Start() { const uint32_t num_threads = std::thread::hardware_concurrency(); for (uint32_t ii = 0; ii < num_threads; ++ii) { threads.emplace_back(std::thread(&ThreadPool::ThreadLoop,this)) } }
2. ThreadPool::ThreadLoop:
Endless loop that waits for new tasks:
void ThreadPool::ThreadLoop() { while (true) { std::function<void()> job; { std::unique_lock<std::mutex> lock(queue_mutex); mutex_condition.wait(lock, [this] { return !jobs.empty() || should_terminate; }); if (should_terminate) { return; } job = jobs.front(); jobs.pop(); } job(); } }
3. ThreadPool::QueueJob:
Adds a new task to the pool:
void ThreadPool::QueueJob(const std::function<void()>& job) { { std::unique_lock<std::mutex> lock(queue_mutex); jobs.push(job); } mutex_condition.notify_one(); }
4. ThreadPool::busy:
Checks if the pool has active jobs:
bool ThreadPool::busy() { bool poolbusy; { std::unique_lock<std::mutex> lock(queue_mutex); poolbusy = !jobs.empty(); } return poolbusy; }
5. ThreadPool::Stop:
Gracefully stops the pool:
void ThreadPool::Stop() { { std::unique_lock<std::mutex> lock(queue_mutex); should_terminate = true; } mutex_condition.notify_all(); for (std::thread& active_thread : threads) { active_thread.join(); } threads.clear(); }
Usage:
thread_pool->QueueJob([] { /* ... */ });
This implementation provides a dynamic thread pool where threads persistently run and wait for tasks to be added.
The above is the detailed content of How to Efficiently Implement a Thread Pool in C 11 to Avoid Repeated Thread Creation and Deletion Overhead?. For more information, please follow other related articles on the PHP Chinese website!