Python 多处理的池常量



我是python中多处理模块的初学者,我只想将并发执行用于我的def函数。此外,我在代码中使用了一些常量,我对它们有问题。代码为(python 3.6.8(:

from multiprocessing import Pool
FIRST_COUNT=10
print("Enter your path")
PATH=input()
some_list=[]
for i in range(10000):
some_list.append(i)  

def func(some_list):
.....

if __name__ == "__main__":
chunks = [some_list[i::4] for i in range(4)]
pool = Pool(processes=4)
pool.map(func,chunks)

当我尝试启动这个程序时,我看到消息输入你的路径5次,5次我需要输入我的路径。即该代码执行1+4次(对于每个进程(。

我想像常量一样使用FIRST_COUNT、PATH和some_list,并且只对func使用多处理。我怎么能做到这一点。请帮帮我。

您应该将代码放入if __name__ == "__main__":中,以便只执行一次

if __name__ == "__main__":
FIRST_COUNT = 10
PATH = input("Enter your path: ")
some_list = list(range(10000))
#some_list = []
#for i in range(10000):
#    some_list.append(i)  
chunks = [some_list[i::4] for i in range(4)]
pool = Pool(processes=4)
results = pool.map(func, chunks)
print(results)

如果要使用FIRST_COUNTPATH,则最好将其作为参数发送给func

您必须在chunks中创建具有FIRST_COUNTPATH的元组

chunks = [(FIRST_COUNT, PATH, some_list[i::4]) for i in range(4)]

函数必须将其作为元组获取,并将其解压缩为

def func(args):
first_count, paht, some_list = args

工作示例

from multiprocessing import Pool
def func(args):
first_count, path, some_list = args
result = sum(some_list)
print(first_count, path, result)
return result 

if __name__ == "__main__":
FIRST_COUNT = 10
PATH = input("Enter your path: ")
some_list = list(range(10000))
#some_list = []
#for i in range(10000):
#    some_list.append(i)  
chunks = [(FIRST_COUNT, PATH, some_list[i::4]) for i in range(4)]
pool = Pool(processes=4)
all_results = pool.map(func, chunks)
print('all results:', all_results)

编辑:您也可以使用starmap()而不是map()

all_results = pool.starmap(func, chunks)

然后您可以使用(无需拆包参数(

def func(first_count, path, some_list):

相关内容

  • 没有找到相关文章

最新更新