蟒蛇 |使用列表元素对方法进行多重处理
我正在尝试使用列表元素对方法进行多重处理。
每次,我都需要传递一组参数以及新的列表项。 我尝试了下面的代码,但无法实现工作并行性。
乐趣(列表元素,arg1,arg2)
from multiprocessing import Process
from multiprocessing import Pool
def fun(each_item, arg1, arg2):
print('start fun')
print("fun in this function")
print('end fun')
def main():
compute_HostList = ['abc.xyz.com', 'def.xyz.com', 'mno.xyz.com']
#Given list
print("Given Compute list: ",compute_HostList)
# Each element as list
New_OS_Compute_List= [[x] for x in compute_HostList]
# Print
print("The new lists of lists: ",New_OS_Compute_List)
for each_item in NewList:
print("item_in_list:", each_item)
p = Process(target=fun, args=(each_item, arg1, arg2))
p.start()
p.join()
"""
#I also tried this using zip, but not working.
for every in New_OS_Compute_List:
tasks = [*zip(every, "OS DBAAS", "dbcs_patching")]
with Pool(5) as pool:
pool.starmap(decideTypeOfPatch, iterable=tasks)
"""
if __name__ == '__main__':
print('start main')
main()
print('end main')
I am trying to multiprocess a method using list elements.
Every time, I need to pass group of arguments along with new list item.
I tried below code, but not able to achieve working parallelism.
fun(list_element,arg1,arg2)
from multiprocessing import Process
from multiprocessing import Pool
def fun(each_item, arg1, arg2):
print('start fun')
print("fun in this function")
print('end fun')
def main():
compute_HostList = ['abc.xyz.com', 'def.xyz.com', 'mno.xyz.com']
#Given list
print("Given Compute list: ",compute_HostList)
# Each element as list
New_OS_Compute_List= [[x] for x in compute_HostList]
# Print
print("The new lists of lists: ",New_OS_Compute_List)
for each_item in NewList:
print("item_in_list:", each_item)
p = Process(target=fun, args=(each_item, arg1, arg2))
p.start()
p.join()
"""
#I also tried this using zip, but not working.
for every in New_OS_Compute_List:
tasks = [*zip(every, "OS DBAAS", "dbcs_patching")]
with Pool(5) as pool:
pool.starmap(decideTypeOfPatch, iterable=tasks)
"""
if __name__ == '__main__':
print('start main')
main()
print('end main')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行
p.start()
后立即执行p.join()
时,它会执行您告诉它执行的操作;-) 也就是说,它运行该进程,然后就坐在那里等待该过程完成。所以你没有得到有用的并行性。因此,不要
将流程对象保存在列表中:
并且在循环结束后等待它们结束:
When you do
p.start()
immediately followed byp.join()
, it does what you told it to do ;-) That is, it runs the process, and then just sits there waiting for the process to finish. So you get no useful parallelism.So instead of
save the process objects in a list instead:
and after that loop is over wait for them to end: