dmytro.poliarush
dmytro.poliarush

Reputation: 383

pygame.event.wait() in pygame python library eats up 100%CPU

I use pygame.event.wait() function in script to lower down CPU usage. I found this idea here:

https://www.pygame.org/docs/ref/event.html#pygame.event.wait

and example of usage here: Pygame waiting the user to keypress a key

I am trying to figure out why the function is not working as intended and where is the error in the script:

import pygame    
from pygame.locals import *    
import threading    


def read_keyboard():    
  pygame.event.clear()    
  while True:    
    event = pygame.event.wait()     # here we wait until user hits keyboard     
    player_input = ''     
    font = pygame.font.Font(None, 50)    
    if event.type == KEYDOWN:    
      if event.unicode == 'h':    
      player_input = 'hello'     
    elif event.type == QUIT:    
      return     

read_keyboard_thread = threading.Thread(target = read_keyboard)

pygame.init()                       
screen = pygame.display.set_mode((480,360))                       
read_keyboard_thread.start()

Upvotes: 1

Views: 914

Answers (1)

dmytro.poliarush
dmytro.poliarush

Reputation: 383

It appears that the issue was caused by how sound is handled in pygame. It appears that CPU utilization is a know issue with pygame and there are different posts about it, particularly this one helped to solve the issue:

https://github.com/pygame/pygame/issues/331

I updated the code to disable some mixer class in pygame and it helped. I am lucky not to need sound in this project :-)

 53 pygame.init()    #  here we start all of the pygame stuff
 54 pygame.mixer.quit()

Finally, there are recommendations to compile pygame from source to solve the issue if mixer is needed

https://github.com/pygame/pygame

Upvotes: 2

Related Questions