This document mostly stems from the resolution of a number of problems I encountered while learning how to program with multiple threads in the Simple DirectMedia Library (SDL). The documentation that comes with the library is not very specific about how to use a number of very useful functions, so here I will try to explain the way I understand these constructs in plain English. A simple but effective main() loop.
The SDL_PollEvent example code from the SDL manual is shown below with minor modifications in red. Beginners might be tempted to use this type of infinite while() loop in their program's main() function to handle events. I know, because I did it once. However, polling for events is a really bad way to track events. SDL_Event event; /* Event structure */ while(nearly infinite loop) { /* Check for events */ while(SDL_PollEvent(&event)) { /* Loop until there are no events left on the queue */ switch(event.type) { /* Process the appropiate event type */ case SDL_KEYDOWN: /* Handle a KEYDOWN event */ printf("Oh! Key press\n"); break; case SDL_MOUSEMOTION: break; case SDL_QUIT: exit(1); default: /* Report an unhandled event */ printf("I don't know what this event is!\n"); } } }
Remember that in most modern operating systems, every program you run is forked as an independent process, and that any ill-designed while() loops contained in your program will cause your process to run far more often than needed to actually maintain full responsiveness. The above code example alone will cause your CPU to peg out at 100% (which is what I've noticed that a lot of SDL-based programs actually *do*). Instead, it helps to think of the main() function as just another thread. You want it to sleep as much as possible.