Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm building a game using SDL in Linux platform.

Now I want to read user input with SDL_GetKeyboardState, but my doubt is wich is the best way using a thread or a timer.

I tried both and I think they work well.

share|improve this question
    
IMO you got a problem here if an event poller eats up 100% CPU. What's your framerate? Do you have a small Sleep(2) in the mail loop? SDL can be really slow if you don't convert all graphics to the screen resolution but an event handler taking CPU speed seems weird. –  Valmond Oct 1 '14 at 8:48
    
If you use double buffering the buffer swap at the end of the frame will block until the swap is allowed to happen. So when you have v-sync on you will save CPU there –  bogglez Oct 1 '14 at 13:46

1 Answer 1

up vote 0 down vote accepted

If you have uncapped FPS, it should eat 100% of your CPU, but most probably you want cap FPS at some reasonable value, say 60 fps, basic implementation can be as follows:

const unsigned int FPS = 60;
const unsigned int DELAY_TIME = 1000 / FPS;
unsigned int frameStart, frameTime;
int spareTime;

// your main loop
while (bRunning) {
    frameStart = SDL_GetTicks();

    // do your stuff

    frameTime = SDL_GetTicks() - frameStart;
    spareTime = DELAY_TIME - frameTime;
    if (spareTime > 0) {
        SDL_Delay((unsigned int)spareTime);
    }
}
share|improve this answer
    
Yes, already know that I have to put a delay to get the desired Fps, but I want to read keyboard apart from the main loop so my question was wich is better a thread o timer? –  Luis Rossell Oct 1 '14 at 12:31
    
@LuisRossell well, I thought your main concern was about 100% CPU time, not the polling itself. If that is not concern, you could remove that information from the question. –  Petr Abdulin Oct 1 '14 at 15:23
    
Yes, you're right it's unclear, thanks for code snippet –  Luis Rossell Oct 1 '14 at 17:13
    
@LuisRossell you shouldn't mark it as answer though, just upvote if you found it useful. –  Petr Abdulin Oct 2 '14 at 1:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.