使用线程池创建线程的方法
时间: 2023-06-19 20:06:33 浏览: 105
使用线程池可以避免频繁地创建和销毁线程,提高程序的性能。下面介绍一种使用线程池创建线程的方法:
1. 首先定义一个线程池类,该类包含一个线程池和一个任务队列:
```c++
#include <thread>
#include <functional>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
using Task = std::function<void()>;
explicit ThreadPool(size_t threadCount = std::thread::hardware_concurrency())
: stop(false)
{
for (size_t i = 0; i < threadCount; ++i) {
workers.emplace_back(
[this]
{
for (;;) {
Task 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();
}
}
);
}
}
~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers)
worker.join();
}
template<class F>
void enqueue(F&& f)
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
private:
std::vector<std::thread> workers;
std::queue<Task> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
```
2. 在主函数中创建线程池,并将任务加入任务队列:
```c++
int main()
{
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.enqueue([i]
{
std::cout << "Task " << i << " is running." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Task " << i << " is done." << std::endl;
});
}
return 0;
}
```
在上面的例子中,我们创建了一个包含4个线程的线程池,并将8个任务加入任务队列中。每个任务会输出一条信息,然后睡眠1秒钟。我们可以看到,线程池会自动调度线程来处理任务,并且每个任务会在一个独立的线程中运行。
阅读全文