From 9913ceb564afd7c5e0c482d548d00268352f0729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Rudowicz?= Date: Fri, 13 Sep 2024 21:46:03 +0200 Subject: [PATCH] Have one worker thread instead of creating threads on demand --- menu.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/menu.py b/menu.py index 3525c97..60c065c 100644 --- a/menu.py +++ b/menu.py @@ -214,10 +214,17 @@ class App: actions)) self.board: IBoard = MenuBoard(self.get_screen_rect(), buttons, theme) self.task_q = Queue() + self.worker_q = Queue() self.screensaver = ClockScreensaver() self.TICKS_UNTIL_SCREENSAVER = screensaver_delay * self.FPS if hide_cursor: pygame.mouse.set_visible(False) + self.worker_thr = Thread(target=self.worker) + self.worker_thr.start() + + def worker(self): + for job in iter(self.worker_q.get, None): + job() def get_screen_rect(self) -> pygame.Rect: return pygame.Rect(0, 0, self.screen.get_width(), self.screen.get_height()) @@ -244,9 +251,8 @@ class App: finally: self.task_q.put(end_thr) - process_thr = Thread(target=thr_fun) - process_thr.start() self.board = MessageBoard(self.get_screen_rect(), action['action_message'], theme=self.theme) + self.worker_q.put(thr_fun) return impl def get_handler(self, action: Action) -> Callable[[], None]: @@ -264,8 +270,7 @@ class App: self.task_q.put(end_thr) self.board = MessageBoard(self.get_screen_rect(), action['action_message'], theme=self.theme) - process_thr = Thread(target=thr_fun) - process_thr.start() + self.worker_q.put(thr_fun) return impl def button_press_handler(self, action: Action) -> Callable[[], None]: @@ -313,11 +318,13 @@ class App: pygame.display.flip() self.clock.tick(self.FPS) + self.worker_thr.join() pygame.quit() def quit(self): self.board = MessageBoard(self.get_screen_rect(), "Exiting...", theme=self.theme) self.running = False + self.worker_q.put(None) def get_url_defs(config_data: dict) -> List[Action]: