Thread pools and executors are essential for managing multiple threads in C++. They help in optimizing resource use and managing thread life cycles efficiently. In C++, you can create a thread pool that allows a defined number of threads to execute tasks concurrently, improving performance for I/O-bound or compute-bound workloads.
Here is a simple example of how to implement a thread pool in C++ using the standard library:
#include
#include
#include
#include
#include
#include
#include
class ThreadPool {
public:
ThreadPool(size_t threads);
~ThreadPool();
template
void enqueue(F&& f);
private:
std::vector<:thread> workers;
std::queue<:function>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
std::atomic stop;
};
ThreadPool::ThreadPool(size_t threads) : stop(false) {
for(size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for(;;) {
std::function task;
{
std::unique_lock<:mutex> lock(this->queue_mutex);
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<:mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(auto &worker: workers) worker.join();
}
template
void ThreadPool::enqueue(F&& f) {
{
std::unique_lock<:mutex> lock(queue_mutex);
tasks.emplace(std::forward(f));
}
condition.notify_one();
}
int main() {
ThreadPool pool(4); // Create a thread pool with 4 threads
// Enqueue tasks
for(int i = 0; i < 8; ++i) {
pool.enqueue([i] {
std::cout << "Task " << i << " is being executed" << std::endl;
});
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?