将loop和thread结合在一起的类 : EventLoopThread. one loop per thread
EventLoopThreadPool
EventLoopThread - subReactor
EventLoopThreadPool - subReactorPool
Thread
可复用于thread Pool。不只用于MuDuo
Thread class 封装了
- 开启/结束/分离线程
- 注册线程函数 threadFunc
- 记录线程信息 如tid,name…
重要成员
- unique_ptr<std::thread> thread_
- 不能直接造thread对象。因为thread对象一构造就开始运行。如果构造了thread对象,那么需要在构造函数初始化,那么一初始化线程就开始运行。
- ThreadFunc func_:thread func
- unique_ptr<std::thread> thread_
- 重要函数
- start : 开启thread,并记录tid(注意lock and cond避免data Race)
- join : 等待thread结束
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26void Thread::start()
{
std::mutex mtx;
std::condition_variable cond;
// start thread
thread_ = std::unique_ptr<std::thread>(new std::thread([&](void)->void{
// 临界区: tid_ , thread func内要写;开启thread的thread要读。
mtx.lock();
tid_ = CurrentThread::tid();
cond.notify_one();
mtx.unlock();
// threadFunc
func_(); // 之后会注册成 EventLoopThread::threadFunc 在这其中创建EventLoop
}));
// 保证start返回时 新线程一定开始运行了。
{
std::unique_lock<std::mutex> lock(mtx);
while(!(tid_ != 0)){
cond.wait(lock);
}
}
started_ = true;
}
EventLoopThread
EventLoopThread: 将loop和thread结合在一起 , 实现 one loop per thread
- 封装了 class Thread 和 EventLoop
- 实现 one loop per thread
- 在 threadFunc中创建 EventLoop 对象 并运行loop.loop():开启循环监听。
- 这样 通过EventLoopThread开启一个thread即代表开启一个loop。开启一个loop即代表开启了一个reactor。
- 所以一个EventLoopThread 其实 就可以看成一个 reactor
重要成员
- EventLoop *loop_ : 记录thread_中创建的EventLoop
- Thread thread_ : 负责开启thread
重要函数
- startLoop : 开启thread,记录loop_*
1
2
3
4
5EventLoop* EventLoopThread::startLoop(){
thread_.start();
// loop_临界区 : lock ; while(!cond) cond.wait ; unlock;
return loop_;
} - threadFunc : 注册在Thread类。跑在thread上。创建EventLoop 并 loop.loop(). 实现 one loop per thread
1
2
3
4
5
6void EventLoopThread::threadFunc()
{
EventLoop loop;
// loop_临界区 lock notify unlock
loop.loop();
}
- startLoop : 开启thread,记录loop_*
EventLoopTheadPool
EventLoopThreadPool:EventLoopThread池子。
- 封装了
重要成员
- vector<unique_ptr
> subReactors_ :管理一堆subReactor,即EventLoopThread - vector<EventLoop*> loops_:记录一堆subReactor的loop
- vector<unique_ptr
重要函数
start : 开启subReactors(EventLoopThreads)
getNextLoop : 轮询到一个subReactor的Loop,返回给上层。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15void EventLoopThreadPool::start(const ThreadInitCallback& cb/* = ThreadInitCallback()*/)
{
for(i<numThreads_)
{
EventLoopThread *t = new EventLoopThread(cb,name);
subReactors_.push_back(unique_ptr<EventLoopThread>(t));
loops_.push_back(t->startLoop());
}
// 整个Server端中只有一个thread,将base放入baseloop(mainthread的eventloop_运行
if(numThreads_ == 0 && cb)
{
cb(baseLoop_);
}
}