I am learn the multiprocessing, but when I want to create a process pool, I meet a question. My code is:
from multiprocessing import Pool, Queue
def read(q):
print("flag")
while not q.empty():
value = q.get()
print('Get %s from queue.' % value)
if __name__=='__main__':
q = Queue()
for i in range(4):
q.put(i)
p = Pool(4)
for i in range(4):
p.apply_async(read, args=(q,))
p.close()
p.join()
print("down")
the child process seems not run, child process have no output. Result is
down
I guess it is related to parameters, so I changed code:
from multiprocessing import Pool, Queue
def read(i):
print("flag")
print(i)
#while not q.empty():
#value = q.get()
#print('Get %s from queue.' % value)
if __name__=='__main__':
q = Queue()
for i in range(4):
q.put(i)
p = Pool(4)
for i in range(4):
p.apply_async(read, args=(i,))
p.close()
p.join()
print("down")
Result is:
flag
0
flag
2
flag
1
flag
3
down
while process have output. So why the previous code can't run correct?
thanks for help.