How do I use thread pools and executors?

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.

Using Thread Pools and Executors in C++

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; }

thread pool executors C++ threads concurrent programming multithreading