Revision history [back]
Interesting, I've replicated this now also. It works intermittently and does not work intermittently. This is true also when run from the DOS Console. The cause is that there is no pr.join() so the parent process can exit before the child running read() has time to do anything. Here is corrected code, which also removes the unneeded while loop in read():
from multiprocessing import Process, Queue
import os, time, random
def write(q):
print ('Process to write: %s' % os.getpid())
a=33
q.put(a)
def read(q):
print ('Process to read: %s' % os.getpid())
value = q.get(True)
print ('Get %s from queue.' % value)
if __name__=='__main__':
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
pw.start()
pr.start()
pw.join()
pr.join()
pr.terminate()
pw.terminate()
print ('done')
Actually, terminate() is redundant with join() because join() waits for the process to terminate unless you send in a timeout arg, which you are not doing. However, I left it in and added one for pw as well, just for completeness. ;-)
Interesting, I've replicated this now also. It works intermittently and does not work intermittently. This is true also when run from the DOS Console. The cause is that there is no pr.join() so the parent process can exit before the child running read() has time to do anything. Here is corrected code, which also removes the unneeded while loop in read():
read():
from multiprocessing import Process, Queue
import os, time, random
random def write(q):
print ('Process to write: %s' % os.getpid())
a=33
q.put(a)
q.put(a) def read(q):
print ('Process to read: %s' % os.getpid())
value = q.get(True)
print ('Get %s from queue.' % value)
value) if __name__=='__main__':
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
pw.start()
pr.start()
pw.join()
pr.join()
pr.terminate()
pw.terminate()
print ('done')
â Actually, terminate() is redundant with join() because join() waits for the process to terminate unless you send in a timeout arg, which you are not doing. However, I left it in and added one for pw as well, just for completeness. ;-)