Thread pools play a crucial role in parallel execution by managing a collection of pre-initialized threads that can be reused to execute tasks.
This approach significantly improves the performance and efficiency of multi-threaded applications.
Key Benefits of Using Thread Pools:
How Thread Pools Work:
Here’s an example of a simple thread pool implementation:
#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
class ThreadPool {
public:
ThreadPool(size_t numThreads);
~ThreadPool();
template <class F>
void enqueue(F&& f);
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
ThreadPool::ThreadPool(size_t numThreads)
: stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(
this->queueMutex);
this->condition.wait(
lock, [this] {
return this->stop ||
!this->tasks.empty();
}
);
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
template <class F>
void ThreadPool::enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
void Log(int number) {
std::cout << "Number: " << number << '\n';
}
int main() {
// Control the number of threads here
ThreadPool pool(4);
std::vector<int> numbers{1, 2, 3, 4, 5};
for (int number : numbers) {
pool.enqueue([number] { Log(number); });
}
}
Number: 1
Number: 5
Number: 3
Number: 4
Number: 2
Key Points:
Using thread pools is a best practice for managing parallel execution in C++, providing a scalable and efficient way to handle concurrent tasks.
Answers to questions are automatically generated and may not have been reviewed.
Multithreading in C++ standard library algorithms using execution policies