我正在尝试在python中学习多处理模块,我编写了这段代码:
from multiprocessing import Process,Queue
import itertools
alphabet = 'abcdefghijklmnopqrstuvwxyz'
max_length = 4
num_procs = 8
procs = []
#Function to get the combinations..Eg: if the chunk is abc:
#The combinations should be a, aa, ab,... abc, abcd, ....., b, ba,bb.....
def doSomething(inp_chunk,q):
for letter in inp_chunk:
for i in range(max_length-1):
for c in itertools.combinations(alphabet,i):
word = letter + ''.join(c)
q.put(word)
def main():
#Divide the alphabet in to chunks based on number of processes
chunk_size = int(len(alphabet) / num_procs)
q = Queue()
#Start Processes and assign chunk of characters to each
for i in range(num_procs):
if i == num_procs-1:
p = Process(target=doSomething,args=(alphabet[i*chunk_size:],q,))
else:
p = Process(target=doSomething,args=(alphabet[i*chunk_size:(i*chunk_size)+chunk_size],q,))
procs.append(p)
p.start()
#Join the processes
for p in procs:
p.join()
print q.get()
if __name__=='__main__':
main()
但由于某种原因,这不起作用。 q.get()的print语句只输出
一
并且流程继续运行。但是当我在没有多处理的情况下运行代码时,只需调用函数而不是for循环中的进程,它就可以工作并给我输出。这花了大约一秒钟。
那我在这里做错了什么? 感谢。
答案 0 :(得分:0)
此声明仅执行一次:
print q.get()
这意味着只会检索和打印放在队列中的第一个字符。将此语句放在循环中以获取其余字符:
while not q.empty():
print q.get()
如果您担心在q.get()
的来电中被屏蔽,请尝试以下操作:
while not q.empty():
try:
print q.get(block=False)
except Queue.Empty:
break
The docs for Queue表示即使Queue.get()
返回Queue.Empty
,对Queue.empty()
的非阻止性调用也可能引发False
异常,所以请记住抓住异常。