线程池
这是一个简单的C++线程池实现。首先,你需要定义一个任务队列数据结构Task,并在其中存储待执行的函数和参数。然后,你需要定义一个线程池类ThreadPool,并在启动时创建指定数量的线程。在每个线程中,你需要循环获取队列中的任务并执行它们。最后,你需要提供一些接口函数来向线程池添加任务和关闭线程池。下面是代码:
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class Task {
public:
template<class Func, class... Args>
explicit Task(Func&& f, Args&&... args) :
func(std::bind(std::forward<Func>(f), std::forward<Args>(args)...)) {}
void operator()() { func(); }
private:
std::function<void()> func;
};
class ThreadPool {
public:
explicit ThreadPool(size_t threadCount) {
for (size_t i = 0; i < threadCount; ++i) {
threads.emplace_back(
[this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mu);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
}
);
}
}
template<class Func, class... Args>
void addTask(Func&& f, Args&&... args) {
{
std::unique_lock<std::mutex> lock(mu);
tasks.emplace(std::forward<Func>(f), std::forward<Args>(args)...);
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mu);
stop = true;
}
condition.notify_all();
for (auto& thread : threads) {
thread.join();
}
}
private:
std::vector<std::thread> threads;
std::queue<Task> tasks;
std::mutex mu;
std::condition_variable condition;
bool stop = false;
};
你可以通过以下代码使用线程池:
ThreadPool pool(4);
auto task1 = [] {
/* 执行任务1 */
};
pool.addTask(task1);
auto task2 = [] {
/* 执行任务2 */
};
pool.addTask(task2);
// 等待所有任务执行完成
// ...
// 关闭线程池
以上代码是一个简单的线程池,仅供参考。如果你想用于生产环境,还需进行一定的优化和安全检查等。
该文介绍了一个C++实现的线程池示例,包括任务队列数据结构Task和线程池类ThreadPool。线程池在启动时创建指定数量的线程,从任务队列中取出并执行任务。提供了添加任务和关闭线程池的接口。
2036

被折叠的 条评论
为什么被折叠?



