-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
44 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
""" | ||
Processes threads one at a time. | ||
""" | ||
|
||
import queue | ||
import threading | ||
|
||
|
||
# Can't use futures because it doesn't have a daemon option so we have to | ||
# impliment our own thread processor. | ||
class ThreadProcessor(threading.Thread): | ||
"""Thread processor.""" | ||
|
||
def __init__(self) -> None: | ||
super().__init__(daemon=True) | ||
self.pending_tasks: queue.Queue = queue.Queue() | ||
self.processing_task: threading.Thread | None = None | ||
self.event = threading.Event() | ||
self.start() | ||
|
||
def run(self) -> None: | ||
"""Process each thread in the queue.""" | ||
while not self.event.wait(0.1): | ||
if self.processing_task is not None: | ||
if not self.processing_task.is_alive(): | ||
self.processing_task.join() | ||
self.processing_task = None | ||
if self.processing_task is not None: | ||
continue | ||
if self.pending_tasks.empty(): | ||
continue | ||
self.processing_task = self.pending_tasks.get() | ||
self.processing_task.start() | ||
|
||
def add(self, thread: threading.Thread) -> None: | ||
"""Queues a thread to be executed.""" | ||
assert thread.daemon is True | ||
self.pending_tasks.put(thread) | ||
|
||
def stop(self) -> None: | ||
"""Stops the thread executor.""" | ||
self.event.set() | ||
self.join() |