Last active
January 28, 2023 22:48
-
-
Save ChrisSwanson/5045640278f766280153689cd5d3df49 to your computer and use it in GitHub Desktop.
python3 multiprocessing example
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
#!/usr/bin/env python3 | |
import multiprocessing | |
import random | |
import time | |
class Worker(multiprocessing.Process): | |
def __init__(self, job_queue): | |
super().__init__() | |
self._job_queue = job_queue | |
def run(self): | |
while True: | |
num = self._job_queue.get() | |
if num is None: | |
break | |
print(f"[{num}] I am a thread.") | |
time.sleep(random.randint(0, 2)) | |
if __name__ == '__main__': | |
jobs = [] | |
job_queue = multiprocessing.Queue() | |
for i in range(5): | |
p = Worker(job_queue) | |
jobs.append(p) | |
p.start() | |
num = random.randint(0, 1000) | |
for item in range(num): | |
job_queue.put(item) | |
# Send None for each worker to check and quit. | |
for j in jobs: | |
job_queue.put(None) | |
for j in jobs: | |
j.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment