[SDL] timers and the event loop

Sean Middleditch elanthis at awesomeplay.com
Sun Jul 1 09:23:28 PDT 2007


Hi everyone,

I'm having trouble groking how to properly handle timers and the event
loop at the same time in SDL.  I'm far more experienced with server
programming, so possibly I'm just approaching things wrong.

The way I'd handle an event loop with timers normally is something like:

  while poll (event_sources, event_source_count, get_next_timer_ms())
    handle_events()
    process_timers()

As timers will be spaced apart by a good amount (usually around 300ms),
I want to be able to both let the app sleep that full time (yay battery
power) when possible.  However, I also want to process events
immediately, as waiting up to 300ms before responding to input is pretty
noticeable.

With SDL, the only possible way I can figure out how to do this is to
set a timer in SDL_Timer, and then have the callback push a user event
to the event queue, and then use SDL_WaitEvents.  Something like:

  function handle_timer
    SDL_PushEvent (... SDL_USEREVENT1 ...)

  function main
    init()

    SDL_SetTimer(get_next_timer_ms(), handle_timer)
    while SDL_WaitEvents()
      if event is SDL_USEREVENT1
        process_timers()
      else
        process_input()

      SDL_SetTimer(get_next_timer_ms(), handle_timer)
  
That feels really clunky and heavyweight to me.  I'm guessing this might
be because Windows or some other port doesn't let you wait on both input
events and a timer expiration like posix poll/select does, but that
doesn't really help me much.

Is that the only way to do this, or is there some other preferred way to
handle this situation that I'm missing?

-- 
Sean Middleditch <elanthis at awesomeplay.com>



More information about the SDL mailing list