One True Event Loop
- by CyberShadow
Simple programs that collect data from only one system need only one event loop. For example, Windows applications have the message loop, POSIX network programs usually have a select/epoll/etc. loop at their core, pure SDL games use SDL's event loop. But what if you need to collect events from several subsystems? Such as an SDL game which doesn't use SDL_net for networking.
I can think of several solutions:
Polling (ugh)
Put each event loop in its own thread, and:
Send messages to the main thread, which collects and processes the events, or
Place the event-processing code of each thread in a critical section, so that the threads can wait for events asynchronously but process them synchronously
Choose one subsystem for the main event loop, and pass events from other subsystems via that subsystem as custom messages (for example, the Windows message loop and custom messages, or a socket select() loop and passing events via a loopback connection).
Option 2.1 is more interesting on platforms where message-passing is a well-developed threading primitive (e.g. in the D programming language), but 2.2 looks like the best option to me.