Pool multiple events and await the first one in C++

20 hours ago 1
ARTICLE AD BOX

If I had multiple sockets to wait for information from, on a POSIX system I would use poll on multiple pollfd for POLLIN roughly as follows...

struct pollfd pollFds[2] = {}; pollFd[0].fd = socket_0; pollFd[1].fd = socket_1; pollFd[0].events = POLLIN; pollFd[1].events = POLLIN; while (true) { int rc = poll(&pollFds, 2, 100); }

...more documentation is here.


However I am working on an OOP interface that looks like this...

class InavjagaGSPIO { protected: int socketfd; public: MoveEvent recvMove(); }; class InavjagaIO { private: std::vector<std::shared_ptr<ServerInavjagaGSPIO>> neighbors; public: MoveEvent getMove(); };

This is a very simplified representation of the interface, but the point is that it does not expose the socket as it provides an abstraction layer above

...and I want to...

wait for input from the first neighbour "x" that sends some

elaborate that one input from

add a new x.recvMove() to this "awaiting pool"

go back to waiting for the others

I almost forgot to mention that there is a timeout on those recv calls that I set earlier (let's say in the constructor).

// https://stackoverflow.com/questions/2876024/linux-is-there-a-read-or-recv-from-socket-with-timeout struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

I have tried looking into the std::async documentation but I couldn't figure how to do this. I think I remember that Python in asyncio had something like that and I found out about it precisely here on Stack Overflow as a comment to an answer of mine, but I am not sure.


Edit 1

The options that I had written down in my development journal before asking here are...

Apparently, there is a few main possibilities…

each InavjagaGSPIO object has a recvMove() method, and we async poll all of them each InavjagaGSPIO object has a recvMove() method, and we have a thread for each one we extract the socketfd from teach InavjagaGSPIO, we create a pollfd for it, then poll each one of them and handle them one by one as described in here we set callbacks using event.h as described in here

Also, one thing worth noticing is that the overhead from poll or events does not scare me as this is not meant to scale excessively and so far a server is meant to host up to 9 clients.


Edit 2

Every single answer under this post is very valuable, thank you for your interest.

I will proceed in one of these days to try the approach described here and then I will report on that. For my own reference, I will be working here.


I came to ask here because I am doing this personal project without AI assistance and I also believe an answer to this question could be useful to others.

Read Entire Article