用c++写一个线程池
时间: 2023-06-30 19:08:07 浏览: 103
以下是一个简单的线程池实现,使用 C++11 标准库中的 `std::thread`,`std::condition_variable`,`std::mutex` 和 `std::queue`:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
class ThreadPool {
public:
ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i)
workers.emplace_back(
[this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::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();
}
}
);
}
template<class F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
worker.join();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
```
使用示例:
```c++
#include <chrono>
void task(int id) {
std::cout << "Task " << id << " started\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Task " << id << " finished\n";
}
int main() {
ThreadPool pool(4);
for (int i = 1; i <= 8; ++i) {
pool.enqueue([i] {
task(i);
});
}
return 0;
}
```
这个例子中,我们创建了一个线程池,指定了线程数为 4。然后,我们向线程池中添加了 8 个任务,每个任务都会睡眠 1 秒钟,然后输出一些信息。
注:这只是一个简单的线程池实现,仅供参考。在实际使用中,需要考虑线程安全、异常处理等问题。
阅读全文