SDL_PollEvent busy‑wait causing high CPU usage in idle loops
26.5K reputation · 30 Jul 2024, 10:09 UTC
When an SDL application runs its main loop with SDL_PollEvent while no input is pending, the function returns immediately and the loop can spin continuously, potentially consuming a full CPU core. This behavior may hide performance problems in rendering or audio subsystems because the observed CPU usage is dominated by the event‑polling loop itself. Developers must decide whether to accept the constant CPU load, insert a delay, or switch to SDL_WaitEvent, each choice affecting latency, power consumption, and thread‑safety guarantees that are implementation‑defined.
What level of CPU usage is acceptable for an idle SDL_PollEvent loop? Does adding a minimal SDL_Delay sufficiently reduce the load without introducing noticeable input lag? How does the thread‑safety of concurrent SDL_PollEvent calls influence the decision to serialize access or use a dedicated input thread?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
2,340 reputation · 30 Jul 2024, 19:24 UTC
SDL_PollEvent does not voluntarily yield the CPU; it simply returns 0 when the queue is empty and -1 on error. On some platforms the underlying implementation may invoke a zero‑timeout wait, but this is not guaranteed and should not be relied upon for portable idle waiting.
Because the event queue is tied to the thread that initialized the video subsystem, calling SDL_PollEvent (or SDL_WaitEvent) from any other thread results in undefined behavior and can corrupt the queue. The safe pattern is to pump events only on that thread, or to serialize access through a mutex if you must forward events to another thread.
- If you need a non‑blocking poll with minimal CPU impact, pair SDL_PollEvent with a short SDL_Delay(1) or use SDL_WaitEventTimeout(1) to let the kernel schedule the thread while keeping sub‑millisecond latency.
- Calling SDL_PumpEvents explicitly before SDL_PollEvent is unnecessary; SDL_PollEvent internally pumps the queue, and a separate pump can cause duplicated event handling.