Does a while loop make full processor consumption?

I need to create a server-side game loop, the problem is how to limit the use of cpu loop.

In my programming experience, the busy cycle always uses maximum CPU utilization. But I am reading the SDL (Simple DirectMedia Layer) code, it has the SDL_Delay(UINT32 ms) function SDL_Delay(UINT32 ms) , and it has a while loop, is the maximum CPU usage required, if not, why not?

https://github.com/eddieringle/SDL/blob/master/src/timer/unix/SDL_systimer.c#L137-158

 do { errno = 0; #if HAVE_NANOSLEEP tv.tv_sec = elapsed.tv_sec; tv.tv_nsec = elapsed.tv_nsec; was_error = nanosleep(&tv, &elapsed); #else /* Calculate the time interval left (in case of interrupt) */ now = SDL_GetTicks(); elapsed = (now - then); then = now; if (elapsed >= ms) { break; } ms -= elapsed; tv.tv_sec = ms / 1000; tv.tv_usec = (ms % 1000) * 1000; was_error = select(0, NULL, NULL, NULL, &tv); #endif /* HAVE_NANOSLEEP */ } while (was_error && (errno == EINTR)); 
+6
source share
3 answers

This code uses select for a timeout. select usually takes a file descriptor and makes the caller wait until an input / output event occurs on fd. It also accepts a timeout argument for maximum latency. Here fd is 0, so no events will occur, and the function will always return when the timeout is reached.

select(3) , which you get from the C library, is the shell of the select(2) system call, which means that the select(3) call will ultimately take you to the kernel. Then, the kernel does not schedule the process unless an I / O event occurs or the timeout is not reached. Thus, the process does not use the processor while waiting.

Obviously, transition to the kernel and process planning lead to delays. Therefore, if you should have very low latency (nanoseconds), you should use expectation.

+3
source

This cycle does not take up the entire processor. It uses one of two different functions to tell the operating system to pause a thread for a given time and allow the other thread to use the processor:

 // First function call - if HAVE_NANOSLEEP is defined. was_error = nanosleep(&tv, &elapsed); // Second function call - fallback without nanosleep. was_error = select(0, NULL, NULL, NULL, &tv); 
+3
source

While the thread is locked in SDL_Delay, it gives the CPU other tasks. If the delay is long enough, the operating system even puts the CPU in standby or stop mode if there is no other job. Please note that this will not work if the delay time is at least 20 milliseconds or so.

However, this is usually the wrong way to do what you are trying to do. What is your external problem? Why does your game loop never stop doing everything that needs to be done at this time, and therefore you need to wait for something to happen so that it has more work? How can you always do endless work?

+1
source

Source: https://habr.com/ru/post/904831/


All Articles