【发布时间】:2016-10-06 16:15:32
【问题描述】:
我一直在研究多处理,并在网站上找到了一个示例。但是,当我尝试在我的 MacBook 视网膜上运行该示例时,没有任何反应。以下是示例:
import random
import multiprocessing
def list_append(count, id, out_list):
"""
Creates an empty list and then appends a
random number to the list 'count' number
of times. A CPU-heavy operation!
"""
for i in range(count):
out_list.append(random.random())
if __name__ == "__main__":
size = 10000000 # Number of random numbers to add
procs = 2 # Number of processes to create
# Create a list of jobs and then iterate through
# the number of processes appending each process to
# the job list
jobs = []
for i in range(0, procs):
out_list = list()
process = multiprocessing.Process(target=list_append,
args=(size, i, out_list))
jobs.append(process)
# Start the processes (i.e. calculate the random number lists)
for j in jobs:
j.start()
# Ensure all of the processes have finished
for j in jobs:
j.join()
print ("List processing complete.")
当我在“list_append”函数中添加一个打印语句后,结果发现没有打印任何内容,所以问题实际上不是j.join(),而是j.start() 位。
【问题讨论】:
-
为什么你有单独的循环来创建、启动和加入进程?
-
@Corn3lius - 我实际上只是从我在网上找到的一个示例中复制和粘贴,否则我试图将它们从循环中取出,但是,我遇到了完全相同的问题。
标签: python-3.4 python-multiprocessing