Skip to content

Commit 9b6b5dd

Browse files
authored
Add poller_t::wait (#680)
* Add poller_t::wait * Update poller_t::wait to return an optional which is nullopt on a timeout * Update poller_t::wait to return std::optional since the trivial optional implementation can only handle trivial types
1 parent 9866e33 commit 9b6b5dd

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

tests/poller.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,31 @@ TEST_CASE("poller remove registered non empty", "[poller]")
178178

179179
const std::string hi_str = "Hi";
180180

181+
#if CPPZMQ_HAS_OPTIONAL
182+
TEST_CASE("poller wait", "[poller]")
183+
{
184+
common_server_client_setup s;
185+
CHECK_NOTHROW(s.client.send(zmq::message_t{hi_str}, zmq::send_flags::none));
186+
zmq::poller_t<int> poller;
187+
int i = 42;
188+
CHECK_NOTHROW(poller.add(s.server, zmq::event_flags::pollin, &i));
189+
auto event = poller.wait();
190+
CHECK(event.has_value());
191+
CHECK(s.server == event.value().socket);
192+
CHECK(&i == event.value().user_data);
193+
}
194+
195+
TEST_CASE("poller wait timeout", "[poller]")
196+
{
197+
common_server_client_setup s;
198+
// No message sent so it will timeout
199+
zmq::poller_t<int> poller;
200+
CHECK_NOTHROW(poller.add(s.server, zmq::event_flags::pollin, nullptr));
201+
auto event = poller.wait(std::chrono::milliseconds{3});
202+
CHECK(!event.has_value());
203+
}
204+
#endif
205+
181206
TEST_CASE("poller poll basic", "[poller]")
182207
{
183208
common_server_client_setup s;

zmq.hpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2781,6 +2781,24 @@ template<typename T = no_user_data> class poller_t
27812781
}
27822782
}
27832783

2784+
#if CPPZMQ_HAS_OPTIONAL
2785+
std::optional<event_type>
2786+
wait(std::chrono::milliseconds timeout = std::chrono::milliseconds{-1})
2787+
{
2788+
event_type event;
2789+
int rc = zmq_poller_wait(poller_ptr.get(),
2790+
reinterpret_cast<zmq_poller_event_t *>(&event),
2791+
static_cast<long>(timeout.count()));
2792+
if (rc == -1) {
2793+
if (zmq_errno() == EAGAIN)
2794+
return {};
2795+
else
2796+
throw error_t();
2797+
}
2798+
return event;
2799+
}
2800+
#endif
2801+
27842802
template<typename Sequence>
27852803
size_t wait_all(Sequence &poller_events, const std::chrono::milliseconds timeout)
27862804
{

0 commit comments

Comments
 (0)