Skip to content

Instantly share code, notes, and snippets.

@wkettler
Last active November 21, 2022 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkettler/8664973f0646e2ab4d2832d1c35843f4 to your computer and use it in GitHub Desktop.
Save wkettler/8664973f0646e2ab4d2832d1c35843f4 to your computer and use it in GitHub Desktop.
Python3 multiprocess producer / consumer example.
#!/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