-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventLoopThread.cpp
More file actions
66 lines (55 loc) · 1.43 KB
/
Copy pathEventLoopThread.cpp
File metadata and controls
66 lines (55 loc) · 1.43 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
#include <muduo/EventLoop.h>
#include <muduo/EventLoopThread.h>
using namespace muduo;
EventLoopThread::EventLoopThread(const IoThreadInitCallback_t& cb, const std::string& n)
: loop_(nullptr)
, name_(n)
, initCb_(cb)
, IoThread_(nullptr)
, isExit_(false)
, mtx_()
, cv_()
{ }
EventLoopThread::~EventLoopThread() noexcept {
isExit_ = true;
if (loop_ != nullptr) {
loop_->Quit(); // 通知loop结束循环
assert(IoThread_->joinable());
IoThread_->join();
}
}
EventLoop* EventLoopThread::Run() {
// TcpServer::ListenAndServe use CAS, So it's no longer needed here
assert(IoThread_.get() == nullptr);
IoThread_.reset(new std::thread([this]() {
this->ThreadFunc();
}));
EventLoop* res = nullptr;
{
std::unique_lock<std::mutex> guard(mtx_);
while (loop_ == nullptr && !isExit_) {
cv_.wait(guard);
}
res = loop_;
}
return res;
}
void EventLoopThread::ThreadFunc() {
EventLoop loop; // create a EventLoop on stack
if (initCb_.operator bool()) {
initCb_(&loop);
}
{
std::lock_guard<std::mutex> guard(mtx_);
if (isExit_ == false) {
loop_ = &loop;
} else {
cv_.notify_one();
return;
}
}
cv_.notify_one();
loop.Loop(); // start loop
std::lock_guard<std::mutex> guard(mtx_);
loop_ = nullptr;
}