在前面我们引入了线程的通信和同步手段,那么为什么还要引入线程池呢?
线程池是一种管理多个线程的技术,它可以减少线程的创建和销毁的开销,提高并发性能。线程池中有一定数量的空闲线程,当有新的任务到来时,就从池中分配一个线程来执行任务,当任务完成后,线程返回池中等待下一个任务。这样可以避免频繁地创建和销毁线程,节省资源和时间。
用C++11实现线程池的基本思路是:
下面是一个简单的示例代码:
#include
#include
#include
#include
#include
#include
#include class ThreadPool {
public:// 构造函数,创建指定数量的线程ThreadPool(size_t num_threads) : stop(false) {for (size_t i = 0; i < num_threads; ++i) {workers.emplace_back([this]() {while (true) {std::function task;// 从任务队列中取出一个任务{std::unique_lock 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();}});}}// 向任务队列中添加一个新的任务templatevoid enqueue(F&& f, Args&&... args) {std::function task = std::bind(std::forward(f), std::forward(args)...); {std::unique_lock lock(queue_mutex);tasks.emplace(task);}condition.notify_one();}// 停止所有线程并回收资源~ThreadPool() {{std::unique_lock lock(queue_mutex);stop = true;}condition.notify_all();for (std::thread& worker : workers) worker.join();}private:std::vector workers; // 线程队列std::queue> tasks; // 任务队列std::mutex queue_mutex; // 互斥锁std::condition_variable condition; // 条件变量bool stop; // 停止标志
};// 测试函数,打印一些信息
void print(int i) {std::cout << "Hello from thread " << i << "\n";
}int main() {ThreadPool pool(4); // 创建4个线程的线程池for (int i = 0; i < 10; ++i) pool.enqueue(print, i); // 添加10个测试任务}
- bar(std::forward
(args)…) 中的 … 是函数参数包展开语法,它会将 args中的每个参数展开成一个单独的函数参数。这意味着,如果 args是一个包含多个参数的参数包,那么这个展开语法将会在函数调用时展开成多个函数参数。 - 例如,假设 args 包含两个参数,一个 int 和一个 double,那么bar(std::forward(args)…) 将会被展开成 bar(std::forward(arg1), std::forward(arg2)),其中 arg1 和 arg2 分别代表参数包中的第一个参数和第二个参数。
- 因此,使用函数参数包展开语法可以将参数包中的参数展开成多个单独的函数参数,从而使得参数可以被正确地转发给其他函数或进行其他操作。
- 在展开语法中,…符号前面的内容是函数模板中的参数包名称(例如:T),而…符号本身是展开语法符号,用于告诉编译器要将参数包展开成一系列参数,并将它们传递给函数func。
- 在这个例子中,逗号操作符不是必需的,因为参数包展开符号已经足够明确地告诉编译器要将参数包展开成一系列参数。
上一篇:手写springmvc步骤
下一篇:数据库面试题——锁