6

I'm designing program that should demonstrate open CV on images. I've noticed very bad concept of basic SDL application - it consists of loop and delay.

while(true) {
    while(event_is_in_buffer(event)) {
        process_event(event);
    }
    do_some_other_stuff();
    do_some_delay(100);       //Program is stuck here, unable to respond to user input
}

This makes the program execute and render even if it is on background (or if re-rendering is not necessary in the first place). If I use longer delay, I get less consumed resources but I must wait longer before events, like mouse click, are processed.
What I want is to make program wait for events, like WinApi does or like socket requests do. Is that possible?
Concept I want:

bool go=true;
while(get_event(event)&&go) {  //Program gets stuck here if no events happen
    switch(event.type){
       case QUIT: go=false;
    }
}
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

1 Answers1

8

You can use SDL_WaitEvent(SDL_Event *event) to wait for an event in the SDL. It will use less resources than the polling loop design you currently have. See the example in this doc:

{
    SDL_Event event;

    while ( SDL_WaitEvent(&event) ) {
        switch (event.type) {
                ...
                ...
        }
    }
}
Étienne
  • 4,773
  • 2
  • 33
  • 58
  • Thank you, this is what i needed. Is there some trick to set time limit for waiting (like with the sockets)? – Tomáš Zato Feb 02 '13 at 21:51
  • 1
    Yeah, you have to use SDL_WaitEventTimeout(SDL_Event* event, int timeout), see this page: http://wiki.libsdl.org/moin.cgi/SDL_WaitEventTimeout – Étienne Feb 02 '13 at 21:59