| 18 | } |
| 19 | |
| 20 | void EventLoopThreadPool::start(const ThreadInitCallback &cb) |
| 21 | { |
| 22 | started_ = true; |
| 23 | |
| 24 | // 循环创建线程 |
| 25 | for(int i = 0; i < numThreads_; ++i) |
| 26 | { |
| 27 | char buf[name_.size() + 32]; |
| 28 | snprintf(buf, sizeof buf, "%s%d", name_.c_str(), i); |
| 29 | // 创建EventLoopThread对象 |
| 30 | EventLoopThread *t = new EventLoopThread(cb, buf); |
| 31 | // 加入此EventLoopThread入容器 |
| 32 | threads_.push_back(std::unique_ptr<EventLoopThread>(t)); |
| 33 | // 底层创建线程 绑定一个新的EventLoop 并返回该loop的地址 |
| 34 | // 此时已经开始执行新线程了 |
| 35 | loops_.push_back(t->startLoop()); |
| 36 | } |
| 37 | |
| 38 | // 整个服务端只有一个线程运行baseLoop |
| 39 | if(numThreads_ == 0 && cb) |
| 40 | { |
| 41 | // 那么不用交给新线程去运行用户回调函数了 |
| 42 | cb(baseLoop_); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // 如果工作在多线程中,baseLoop_(mainLoop)会默认以轮询的方式分配Channel给subLoop |
| 47 | EventLoop *EventLoopThreadPool::getNextLoop() |