线程池学习2
思路:
线程池: 当进行并行的任务作业操作时,线程的建立与销毁的开销是阻碍性能进步的关键,因此需要在线程池内创建多个线程,无限循环从任务队列中取走任务并执行,提高性能。
函数理解
std::unique_lock介绍
std::unique_lock比std::lock_guard更灵活,这种灵活性主要体现在以下两点:
- lock_guard在构造时或者构造前(std::adopt_lock)就已经获取互斥锁,并且在作用域内保持获取锁的状态,直到作用域结束;而unique_lock在构造函数时或者构造后(std::defer_lock)获取锁,在作用域范围内可以手动获取锁和释放锁,作用域结束时如果已经获取锁则自动释放。
- lock_guard锁的持有只能在lock_guard对象的作用域范围内,作用域范围之外锁被释放,而unique_lock对象支持移动操作,可以将unique_lock对象通过函数返回值返回,这样锁转移到外部unique_lock对象中,延长锁的持有时间。
std::lock_guard<std::mutex> locker(_pool->mtx)介绍
这句话是锁定mtx
这个互斥量,避免其他线程获取这个互斥量吗? 还是说,只锁住这句话之后的代码块,避免别的线程访问该代码块的共享变量??
答:是锁住这个互斥量。因为一旦有一个线程的某段代码锁住了这个互斥量,其他线程就获取不了这个锁的权限了。使用同一个互斥量在不同的地方锁住,是因为这几个地方代码肯定会访问同一个变量(或者说共享内存区域)。
不止是该代码块的共享变量被锁了,该代码块的共享内存区域都被锁了。
综上,locker将这个变量锁好,具体作用是:
- 同一位置A处上锁,是防止线程1在位置A
写
的时候,线程2在位置A读
或写
该内存区域;或者,防止线程1在位置A读
的时候,线程2在位置A写
该内存区域; - 不同位置A和B都上锁,是防止线程1在位置A
读
的时候,线程2在位置B写
该内存区域,或者线程1在位置A写
的时候,线程2在位置B读
或写
该内存区域。
void *arg
void的字面意思是“无类型”,void *则为“无类型指针”,void *可以指向任何类型的数据。
线程池代码与测试
代码
threadpool.h
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
#include <functional>
#include <cassert>
class ThreadPool{
public:
explicit ThreadPool(size_t threadCount = 8): _pool(std::make_shared<Pool>()){
assert(threadCount > 0);
for(size_t i = 0; i < threadCount; i++){
std::thread([pool = _pool]{
std::unique_lock<std::mutex> locker(pool->mtx);
while(true){
if(!pool->tasks.empty()){
auto task = std::move(pool->tasks.front());
pool->tasks.pop();
locker.unlock();
task();
locker.lock();
}else if(pool->isClosed) break;
else pool->cond.wait(locker);
}
}).detach(); // detach表示线程分离
}
}
ThreadPool() = default;
ThreadPool(ThreadPool &&) = default;
~ThreadPool(){
if(static_cast<bool>(_pool)){
{
std::lock_guard<std::mutex> locker(_pool->mtx);
_pool->isClosed = true;
}
_pool->cond.notify_all();
}
}
template<class F>
inline void AddTask(F &&task){
{
std::lock_guard<std::mutex> locker(_pool->mtx);
_pool->tasks.emplace(std::forward<F>(task));
}
_pool->cond.notify_one(); // 添加一个线程,就唤醒一个消费者(表示生产者生产了一个线程)
}
private:
struct Pool{
// 池子
std::mutex mtx; // 互斥锁
std::condition_variable cond; // 条件变量
bool isClosed; // 是否关闭
std::queue<std::function<void()>> tasks; // 队列(保存的是任务)
};
std::shared_ptr<Pool>_pool;
};
#endif
test_threadpool.cpp
#include "threadpool.h"
#include<iostream>
#include<random>
#include<algorithm>
using namespace std;
void taskFunc(void* arg){
int num = *static_cast<int*>(arg);
thread::id this_thread_id = this_thread::get_id();
cout << "ThreadId = " << this_thread_id << " num = " << num << endl;
// Sleep(10);
std::this_thread::sleep_for(std::chrono::milliseconds(10));//睡眠10毫秒
}
int main(){
ThreadPool pool(4);
for(int i = 0; i < 100; i++){
int *num = new int(i);
pool.AddTask(function<void()>(bind(&taskFunc, num)));
}
// 睡眠1000毫秒 这个必不可少,等到所有进程都打印完毕才允许退出
// 线程池需不需要增加一个等待线程结束的才允许退出的代码呢?
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return 0;
}
编译:
gcc test_threadpool.cpp -o test_threadpool
执行:
./test_threadpool
执行结果:
结果分析:
id中出现的为四个进程,并且数字0~99全部得以打印,说明这个线程池运行是正常的。
参考:
2、多线程锁住的是什么;