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函數打印一個數字。