-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventLoopThreadPool.cc
More file actions
80 lines (60 loc) · 1.91 KB
/
Copy pathEventLoopThreadPool.cc
File metadata and controls
80 lines (60 loc) · 1.91 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "EventLoopThreadPool.hpp"
#include "EventLoopThread.hpp"
EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseloop, std::string &nameArg)
: baseLoop_(baseloop)
, name_(nameArg)
, started_(false)
, numThreads_(0)
, next_(0)
{}
EventLoopThreadPool::~EventLoopThreadPool() {
// 新的 Loop 都是线程的栈对象,会随着线程结束而析构
// 指向的每个线程的句柄都是智能指针,会自动释放
}
void EventLoopThreadPool::start(const ThreadInitCallback &cb)
{
started_ = true;
for(int i = 0; i < numThreads_; ++i)
{
char buf[name_.size()+32];
snprintf(buf, sizeof(buf), "%s%d", name_.c_str(), i);
//新建一个EventLoopTread对象,只有当使用start线程才会开始运行
EventLoopThread* t = new EventLoopThread(cb, buf);
// 构造一个临时变量,相当于右值,进行资源转移
threads_.emplace_back( std::unique_ptr<EventLoopThread>(t) );
// 启动该子线程的会再创建一个子子线程
// 但是子线程会返回结束,子子线程会保留,执行新建subloop的循环
loops_.emplace_back(t->startLoop());
}
// 如果整个服务就只有一个线程,那就只运行baseloop
if (numThreads_ == 0 && cb != nullptr)
{
cb(baseLoop_);
}
}
// 如果工作在多线程中,baseloop_默认以轮询的方式,分配 channel 给 subloop
EventLoop *EventLoopThreadPool::getNextLoop()
{
EventLoop *loop = baseLoop_;
if (!loops_.empty())
{
loop = loops_[next_];
++next_;
if (next_ >= loops_.size())
{
next_ = 0;
}
}
return loop;
}
std::vector<EventLoop *> EventLoopThreadPool::getAllLoops()
{
if (loops_.empty())
{
return std::vector<EventLoop* >(1, baseLoop_);
}
else
{
return loops_;
}
}