C++线程池的使用

一:为什么要使用线程池?

1.为了减少创建和销毁线程的次数,线程池在设计的时候已经创建好了线程,直接使用即可.

2.实现多线程并发,提高管理效率,比如说有10个人去银行办业务,有3个窗口柜员,柜员就相当于3个线程,调用10个客户,每个柜员可以同时一次处理一个客户。假如没有线程池,这10个人就去1个窗口排队办业务.

二多线程

相关的函数:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

 Compile and link with -pthread

pthread_t *thread :  

第一个参数为指向线程标识符的指针。

第二个参数用来设置线程属性。

第三个参数是线程运行函数的地址。

最后一个参数是运行函数的参数。

以下是一个简单的 C++ 线程池使用示例: ```c++ #include <iostream> #include <thread> #include <vector> #include <queue> #include <mutex> #include <condition_variable> class ThreadPool { public: ThreadPool(int threadCount) : stop(false) { for (int i = 0; i < threadCount; ++i) threads.emplace_back([this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queueMutex); 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(queueMutex); tasks.emplace(std::forward<F>(f)); } condition.notify_one(); } ~ThreadPool() { { std::unique_lock<std::mutex> lock(queueMutex); stop = true; } condition.notify_all(); for (std::thread &worker : threads) worker.join(); } private: std::vector<std::thread> threads; std::queue<std::function<void()>> tasks; std::mutex queueMutex; std::condition_variable condition; bool stop; }; int main() { ThreadPool pool(4); for (int i = 0; i < 8; ++i) { pool.enqueue([i] { std::cout << "Task " << i << " started" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "Task " << i << " finished" << std::endl; }); } return 0; } ``` 这个示例中,线程池的构造函数接受一个 int 类型的参数,指定线程池中的线程数量。enqueue() 方法用于将一个任务提交到线程池中,这个方法可以接受任何可调用对象。 在主函数中,我们创建了一个线程池,然后提交了 8 个任务到线程池中。每个任务都会输出一些文本,然后休眠一秒钟,最后再输出一些文本。注意到我们并没有显式地创建任何线程,所有的线程都是由线程池自动管理的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值