Skip to content
Advertisement

How can a busy-wait loop be avoided for an event driven program?

I’m coding a chess game in python using pygame. One of the common tasks is the need to handle events, and the only way I know how to do it is like this:

while True:
    for event in pygame.event.get():  
        # handle event

The while loop just keeps spinning, which is inefficient. In embedded programming, you can send the cpu to sleep until there is an interrupt. Is there a way to do something similar in python, having the loop wait for events?

pygame.time.Clock.tick (as covered in “Pygame clock and event loops“) can limit the number of frames/iterations per second, which is not what I want to accomplish.

Advertisement

Answer

It sounds to me like you should use

pygame.event.wait()

Returns a single event from the queue. If the queue is empty this function will wait until one is created…While the program is waiting it will sleep in an idle state.

See this documentation.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement