Last active
November 21, 2022 03:40
-
-
Save wkettler/8664973f0646e2ab4d2832d1c35843f4 to your computer and use it in GitHub Desktop.
Python3 multiprocess producer / consumer 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 logging | |
from multiprocessing import Process, Pool, Manager | |
import random | |
import time | |
def init(queue): | |
global q | |
q = queue | |
def producer(id): | |
for i in range(10): | |
q.put((id, random.randint(0,999))) | |
def consumer(q): | |
count = 0 | |
while True: | |
item = q.get() | |
if item is None: | |
break | |
id, num = item | |
print(f'Process {id} : {num}') | |
count += 1 | |
print(f'Processed {count} items') | |
if __name__ == '__main__': | |
count = 5 | |
queue = Manager().Queue() | |
c = Process(target=consumer, args=[queue]) | |
c.start() | |
with Pool(count, init, [queue]) as pool: | |
pool.map(producer, [x for x in range(count)]) | |
queue.put(None) | |
c.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment