waiting for 2 different events in a single thread
- by João Portela
component A (in C++) - is blocked waiting for alarm signals (not relevant) and IO signals (1 udp socket). has one handler for each of these.
component B (java) - has to receive the same information the component A udp socket receives. periodicaly gives instructions that should be sent through component A udp socket.
How to join both components?
it is strongly desirable that:
the changes to attach component B to component A are minimal (its not my code and it is not very pleasent to mess with).
the time taken by the new operations (usually communicating with component B) interfere very little with the usual processing time of component A - this means that if the operations are going to take a "some" time I would rather use a thread or something to do them.
note: since component A receives udp packets more frequently that it has component B instructions to forward, if necessary, it can only forward the instructions (when available) from the IO handler.
my initial ideia was to develop a component C (in C++) that would sit inside the component A code (is this called an adapter?) that when instanciated starts the java process and makes the necessary connections (that not so little overhead in the initialization is not a problem).
It would have 2 stacks, one for the data to give component B (lets call it Bstack) and for the data to give component A (lets call it Astack). It would sit on its thread (lets call it new-thread) waiting for data to be available in Bstack to send it over udp, and listen on the udp socket to put data on the Astack. This means that the changes to component A are only: when it receives a new UDP packet put it on the Bstack, and if there is something on the Astack sent it over its UDP socket (I decided for this because this socket would only be used in the main thread).
One of the problems is that I don't know how to wait for both of these events at the same time using only one thread.
so my questions are:
Do I really need to use the main thread to send the data over component A socket or can I do it from the new-thread? (I think the answer is no, but I'm not sure about race conditions on sockets)
how to I wait for both events?
boost::condition_variable or something similar seems the solution in the case of the stack and boost::asio::io_service io_service.run() seems like the thing to use for the socket.
Is there any other alternative solution for this problem that I'm not aware of?
Thanks for reading this long text but I really wanted you to understand the problem.