在windows中,必须先检查进程是否为main,才能使用multiprocessing,否则会出现死循环。
我试图将进程的名称更改为子进程的名称,以便在我调用的类或函数中使用多处理,但没有运气。这甚至可能吗?到目前为止,我没有使用多处理,除非它使用的是主进程。
如果可能的话,有人可以提供一个示例,说明如何在从更高进程调用的类或函数中使用多处理?谢谢。
编辑:
这是一个示例 - 第一个有效,但所有内容都在 1 个文件中完成:simplemtexample3.py:
import random
import multiprocessing
import math
def mp_factorizer(nums, nprocs):
#schtze den prozess
#print __name__
if __name__ == '__main__':
out_q = multiprocessing.Queue()
chunksize = int(math.ceil(len(nums) / float(nprocs)))
procs = []
for i in range(nprocs):
p = multiprocessing.Process(
target=worker,
args=(nums[chunksize * i:chunksize * (i + 1)],
out_q))
procs.append(p)
p.start()
# Collect all results into a single result dict. We know how many dicts
# with results to expect.
resultlist = []
for i in range(nprocs):
temp=out_q.get()
index =0
#print temp
for i in temp:
resultlist.append(temp[index][0][0:])
index +=1
# Wait for all worker processes to finish
for p in procs:
p.join()
resultlist2 = [x for x in resultlist if x != []]
return resultlist2
def worker(nums, out_q):
""" The worker function, invoked in a process. 'nums' is a
list of numbers to factor. The results are placed in
a dictionary that's pushed to a queue.
"""
outlist = []
for n in nums:
newnumber= n*2
newnumberasstring = str(newnumber)
if newnumber:
outlist.append(newnumberasstring)
out_q.put(outlist)
l = []
for i in range(80):
l.append(random.randint(1,8))
print mp_factorizer(l, 4)
但是,当我尝试从另一个文件调用 mp_factorizer 时,它不起作用,因为if __name__ == '__main__'
:
简单示例.py
import random
import multiprocessing
import math
def mp_factorizer(nums, nprocs):
#schtze den prozess
#print __name__
if __name__ == '__main__':
out_q = multiprocessing.Queue()
chunksize = int(math.ceil(len(nums) / float(nprocs)))
procs = []
for i in range(nprocs):
p = multiprocessing.Process(
target=worker,
args=(nums[chunksize * i:chunksize * (i + 1)],
out_q))
procs.append(p)
p.start()
# Collect all results into a single result dict. We know how many dicts
# with results to expect.
resultlist = []
for i in range(nprocs):
temp=out_q.get()
index =0
#print temp
for i in temp:
resultlist.append(temp[index][0][0:])
index +=1
# Wait for all worker processes to finish
for p in procs:
p.join()
resultlist2 = [x for x in resultlist if x != []]
return resultlist2
def worker(nums, out_q):
""" The worker function, invoked in a process. 'nums' is a
list of numbers to factor. The results are placed in
a dictionary that's pushed to a queue.
"""
outlist = []
for n in nums:
newnumber= n*2
newnumberasstring = str(newnumber)
if newnumber:
outlist.append(newnumberasstring)
out_q.put(outlist)
开始implemtexample.py
import simplemtexample as smt
import random
l = []
for i in range(80):
l.append(random.randint(1,8))
print smt.mp_factorizer(l, 4)