/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+ * Copyright (c) 2018-present Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
std::lock_guard<Mutex> lock(mutex);
- if (this->listener.find(fd) != this->listener.end())
- THROW(ErrCode::RuntimeError) << "Event is already registered.";
+ if (this->listener.find(fd) != this->listener.end()) {
+ WARN(VIST) << "Event is already registered.";
+ return;
+ }
::epoll_event event;
std::memset(&event, 0, sizeof(epoll_event));
this->addHandler(this->wakeupSignal.getFd(), wakeup);
}
-void Mainloop::wait(int timeout)
+void Mainloop::wait(int timeout, Stopper stopper)
{
int nfds = 0;
do {
if (nfds == 0) {
DEBUG(VIST) << "Mainloop is stopped by timeout.";
- this->stopped = true;
+
+ if (stopper())
+ this->stopped = true;
+
return;
}
}
}
-void Mainloop::run(int timeout)
+void Mainloop::run(int timeout, Stopper stopper)
{
this->stopped = false;
this->prepare();
+
+ if (stopper == nullptr)
+ stopper = []() -> bool { return true; };
+
while (!this->stopped)
- this->wait(timeout);
+ this->wait(timeout, stopper);
}
void Mainloop::stop(void)
public:
using OnEvent = std::function<void(void)>;
using OnError = std::function<void(void)>;
+ using Stopper = std::function<bool(void)>;
Mainloop();
virtual ~Mainloop();
void addHandler(const int fd, OnEvent&& onEvent, OnError&& = nullptr);
void removeHandler(const int fd);
- void run(int timeout = -1);
+ /// Stopper is a predicate what returns a condition to stop mainloop
+ /// when timeout is occured.
+ void run(int timeout = -1, Stopper = nullptr);
void stop(void);
private:
bool prepare(void);
- void wait(int timeout);
+ void wait(int timeout, Stopper stopper);
void dispatch(int size);
Mutex mutex;