Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent SDL program from consuming extra resources

Tags:

c++

sdl

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;
    }
}
like image 753
Tomáš Zato - Reinstate Monica Avatar asked Feb 02 '13 21:02

Tomáš Zato - Reinstate Monica


Video Answer


1 Answers

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) {
                ...
                ...
        }
    }
}
like image 199
Étienne Avatar answered Oct 31 '22 03:10

Étienne