Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event-driven programming: callback vs message polling

I've been looking into OpenGL programming as a C++ programmer, and have seen two primary ways of dealing with event-driven programming: message polling or callback functions.

  • I see that the native Win32API uses a callback function, which is triggered by the DispatchMessage function.

  • SDL (based on the tutorials) also use some sort of callback or callback-like programming.

  • GLFW also uses callbacks.

  • SFML lets the programmer poll for individual messages anywhere in the code, usually in a loop, forming the message loop.

  • The X Window system, based on what I have seen, also uses message polling.

Clearly, since event systems exist in prominent environments, each must have an advantage. I was hoping someone could tell me the advantages and disadvantages of each. I am thinking of writing some programs which would heavily depend on event-driven programming, and would like to make the best decision on which path to take.

like image 356
ithenoob Avatar asked Sep 30 '22 12:09

ithenoob


1 Answers

This isn't going to be complete, but here's a few things that come to mind...

I've only ever used GL for 3D, and haven't really done much in the way of GUIs. Polling for events is pretty common. More precisely, polling in a main rendering loop which processes all events in a queue and then moves on to rendering. This is because you re-render everything from scratch each frame after collecting all events and using them to update the scene's 3D state. Since a screen can only display images at a limited frame rate, it's also common to sleep during polling as any state updates won't get shown till later even if their events are triggered sooner.

  • If you were to process events exactly as they happen, such as part-way through drawing, then you have race conditions. Dealing with this may be an unnecessary hastle.

  • If you have anything animating then you already have a loop and polling is a trivial cost in contrast.

  • If your events are very infrequent, then you don't need to re-draw often so having a thread active and polling is a little in-efficient.

  • It'll be quite bad if events pile up and you're re-drawing for each one. You might find you're re-drawing more often than using a loop to process all events and render once.

I think the main issue with polling is for inactive windows that aren't in focus. Lets say you minimize your GL app. You know it won't receive any events so polling is useless. So is drawing for that matter.

Another issue is response latency. This is quite important for something like capturing mouse movement in a game. As long as you poll for events in the right order (input→update→display) this is generally OK. However, vsync can mess with the timing by delaying frames from being displayed.

like image 143
jozxyqk Avatar answered Oct 04 '22 02:10

jozxyqk