生产者与消费者模式
简单来说就是生产者不停地生产任务 然后把任务放在一个任务队列里面 消费者再从这个任务队列里面去拿出任务 执行任务
先来思考一个线程池需要些什么
1肯定需要线程就需要用到线程的封装
2需要用到互斥锁 协调多个线程对于共享资源的访问
3还需要一个装任务的队列
4条件变量condition_variable管理线程
一个基于生产者与消费者模式的线程池
#include<iostream>
#include<thread>
#include<mutex>
#include<string>
#include<condition_variable>
#include<queue>
#include<vector>
#include<functional>
using namespace std;
queue<int> tasks;
mutex mtx;
condition_variable condition;
void poudcer() {
for (int i = 0; i < 10; i++) {
unique_lock<mutex> lock(mtx);
tasks.push(i);
condition.notify_one();
cout << "task:" << i << endl;
}
std::this_thread::sleep_for(std::chrono::microseconds(10000));
}
void consumer() {
while (1) {
unique_lock<mutex> lock(mtx);
condition.wait(lock, []() {return !tasks.empty(); });
int value = tasks.front();
tasks.pop();
cout << "get:" << value << endl;
}
}
int main() {
thread demo(poudcer);
thread demo1(consumer);
demo.join();
demo1.join();
}
一个基于c++11新特性的线程池
#include<iostream>
#include<thread>
#include<mutex>
#include<string>
#include<condition_variable>
#include<queue>
#include<vector>
#include<functional>
using namespace std;
class ThreadPool {
ThreadPool(int numthreads) {
for (int i = 0; i < numthreads; i++) {
threads.emplace_back([this] {
while (1) {
unique_lock<mutex> lock(mtx);
condition.wait(lock, [this] {
return !tasks.empty() || stop;
});
if (stop) {
return;
}
function<void()> task(move(tasks.front()));
tasks.pop();
lock.unlock();
task();
}
});
}
}
~ThreadPool() {
unique_lock<mutex> lock(mtx);
lock.unlock();
stop = true;
condition.notify_all();
for (auto& job : threads) {
job.join();
}
}
private:
vector<thread> threads;
queue<function<void>> tasks;
mutex mtx;
condition_variable condition;
bool stop //判断线程终止
};