Created
September 11, 2022 00:15
-
-
Save ruby0b/c12fba10d5f3a9611a84a338b161f96f to your computer and use it in GitHub Desktop.
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
from queue import Queue | |
from threading import Thread | |
from typing import Callable, Iterable | |
def job_worker(jobs: Queue, results: list): | |
while not jobs.empty(): | |
job = jobs.get() | |
results.append(job()) | |
jobs.task_done() | |
def run_in_threaded_queue(tasks: Iterable[Callable], worker_amount: int) -> list: | |
jobs = Queue() | |
for task in tasks: | |
jobs.put(task) | |
results = [] | |
threads = [] | |
for _ in range(worker_amount): | |
thread = Thread(target=job_worker, args=(jobs, results)) | |
thread.start() | |
threads.append(thread) | |
# process the queue | |
jobs.join() | |
# make sure the threads stop | |
for thread in threads: | |
thread.join() | |
return results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment