C++线程池的实现方法可以使用C++中的多线程库,如std::thread和std::mutex等来实现。以下是一个简单的C++线程池的实现方法:
下面是一个简单的C++线程池的示例代码:
#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back([this]() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this]() {
return stop || !tasks.empty();
});
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread& thread : threads) {
thread.join();
}
}
template<typename Func, typename... Args>
void enqueue(Func&& func, Args&&... args) {
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
}
condition.notify_one();
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
// 示例任务函数
void printNumber(int number) {
std::cout << "Number: " << number << std::endl;
}
int main() {
ThreadPool pool(4);
for (int i = 0; i < 10; ++i) {
pool.enqueue(printNumber, i);
}
return 0;
}
上述代码使用了C++11的特性,包括std::thread、std::mutex、std::condition_variable和std::function等。它创建了一个大小为4的线程池,然后向线程池中添加了10个任务,每个任务都是调用printNumber函数打印一个数字。