Skip to content

Instantly share code, notes, and snippets.

@mcstafford-git
Created March 6, 2018 23:19
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 mcstafford-git/a811ca84bddc292ecafd72f998fa3d78 to your computer and use it in GitHub Desktop.
Save mcstafford-git/a811ca84bddc292ecafd72f998fa3d78 to your computer and use it in GitHub Desktop.
# variable scope, lifetime
# modified from stackoverflow https://goo.gl/Gy5Ai7
import multiprocessing
import os
def hey(pid, message):
global i
global queue
denominator = None
try:
denominator = queue.qsize()
except NameError:
pass
print(
'{}:{}/{}'.format(pid, i, denominator),
message,
)
i += 1
def worker_main(queue):
hey(os.getpid(), 'init')
while True:
item = queue.get(True)
hey(os.getpid(), item)
i = 0
hey(os.getpid(), 'BEFORE')
queue = multiprocessing.Queue()
pool = multiprocessing.Pool(processes=3, initializer=worker_main, initargs=(queue, ))
for i in range(5):
queue.put('hello')
queue.put('world')
hey(os.getpid(), 'DURING')
while queue.qsize():
pass
hey(os.getpid(), 'AFTER')
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment