Thread Pooling in C 11
Introduction
Thread pooling is a technique for managing a set of threads that can be dynamically assigned tasks. It offers several advantages over creating and destroying threads on each task, including improved performance and resource efficiency.
Understanding Thread Pooling
In C 11, a thread pool is typically implemented using a combination of threads, mutexes, and condition variables. Threads are created and started in the background, and tasks are added to a queue. Workers constantly monitor the queue, waiting for new tasks to become available. Once a task is available, a worker will retrieve it and execute it.
Creating a Thread Pool
To create a thread pool, we can define a 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; };
Managing the Thread Pool
Worker Thread Loop
Each worker thread runs an infinite loop to wait for and execute 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(); } }
Using the Thread Pool
To use the thread pool, simply create an instance and call QueueJob to add tasks:
ThreadPool thread_pool; thread_pool.Start(); thread_pool.QueueJob([] { /* ... */ });
Advantages of Thread Pooling
The above is the detailed content of How Does Thread Pooling Work in C 11?. For more information, please follow other related articles on the PHP Chinese website!