Skip to content

Commit 55232ba

Browse files
authored
Add the moveToCurrentThread() method to EventLoop (#93)
1 parent 880ca0a commit 55232ba

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

trantor/net/EventLoop.cc

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,19 @@ EventLoop::EventLoop()
6767
poller_(Poller::newPoller(this)),
6868
currentActiveChannel_(nullptr),
6969
eventHandling_(false),
70-
timerQueue_(new TimerQueue(this))
70+
timerQueue_(new TimerQueue(this)),
71+
threadLocalLoopPtr_(&t_loopInThisThread)
7172
#ifdef __linux__
7273
,
7374
wakeupFd_(createEventfd()),
7475
wakeupChannelPtr_(new Channel(this, wakeupFd_))
7576
#endif
7677
{
77-
assert(t_loopInThisThread == 0);
78+
if (t_loopInThisThread)
79+
{
80+
LOG_FATAL << "There is already an EventLoop in this thread";
81+
exit(-1);
82+
}
7883
t_loopInThisThread = this;
7984
#ifdef __linux__
8085
wakeupChannelPtr_->setReadCallback(std::bind(&EventLoop::wakeupRead, this));
@@ -315,4 +320,29 @@ void EventLoop::wakeupRead()
315320
if (ret < 0)
316321
LOG_SYSERR << "wakeup read error";
317322
}
323+
324+
void EventLoop::moveToCurrentThread()
325+
{
326+
if (isRunning())
327+
{
328+
LOG_FATAL << "EventLoop cannot be moved when running";
329+
exit(-1);
330+
}
331+
if (isInLoopThread())
332+
{
333+
LOG_WARN << "This EventLoop is already in the current thread";
334+
return;
335+
}
336+
if (t_loopInThisThread)
337+
{
338+
LOG_FATAL << "There is already an EventLoop in this thread, you cannot "
339+
"move another in";
340+
exit(-1);
341+
}
342+
*threadLocalLoopPtr_ = nullptr;
343+
t_loopInThisThread = this;
344+
threadLocalLoopPtr_ = &t_loopInThisThread;
345+
threadId_ = std::this_thread::get_id();
346+
}
347+
318348
} // namespace trantor

trantor/net/EventLoop.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,17 @@ class EventLoop : NonCopyable
151151
{
152152
return callingFuncs_;
153153
}
154+
/**
155+
* @brief Move the EventLoop to the current thread, this method must be
156+
* called before the loop is running.
157+
*
158+
*/
159+
void moveToCurrentThread();
154160

155161
private:
156162
void abortNotInLoopThread();
157163
bool looping_;
158-
const std::thread::id threadId_;
164+
std::thread::id threadId_;
159165
bool quit_;
160166
std::unique_ptr<Poller> poller_;
161167

@@ -181,6 +187,7 @@ class EventLoop : NonCopyable
181187
#else
182188
size_t index_{std::numeric_limits<size_t>::max()};
183189
#endif
190+
EventLoop **threadLocalLoopPtr_;
184191
};
185192

186193
} // namespace trantor

0 commit comments

Comments
 (0)