What is the method of using a thread pool in C++?
In C++, using a thread pool typically involves the following steps:
- conversation
- Create a class for a thread pool that consists of a thread pool container and a task queue.
- Define a task class that includes a function pointer and function parameters.
- Define a method in the ThreadPool class to add tasks to the task queue.
- Define a method in the thread pool class to execute tasks, which retrieves tasks from the task queue and performs them.
- Create a thread pool object in the main function and call the method to add tasks to it.
- By calling the method to start the execution of tasks in the thread pool object, the added tasks will be automatically executed by the thread pool.
Here is a simple example code of a thread pool in C++.
#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <functional>
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(std::bind(&ThreadPool::worker, this));
}
}
template <class F, class... Args>
void addTask(F&& f, Args&&... args) {
tasks.emplace(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mutex);
stop = true;
}
condition.notify_all();
for (auto& thread : threads) {
thread.join();
}
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex mutex;
std::condition_variable condition;
bool stop;
void worker() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex);
condition.wait(lock, [this]() { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
}
};
void printHello() {
std::cout << "Hello" << std::endl;
}
int main() {
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.addTask(printHello);
}
return 0;
}
In the above example, the ThreadPool class contains a ThreadPool container threads and a task queue tasks. Tasks can be added to the task queue by calling the addTask method. In the worker method, ThreadPool threads will continuously take tasks from the task queue and execute them. In the main function, a ThreadPool object with 4 threads is created and 8 tasks to print “Hello” are added.