python - 您能否分享一些关于在使用多处理时处理列表的见解?(给出一个场景)
问题描述
设想
我有一个 longlist
其中每个元素都是 a string
,现在我想通过使用一些函数对每个元素执行相同的操作。考虑到list
的长度,我想用它multiprocessing
来创建一些Process
来处理它list
。每个Process
只处理列表的一部分元素。以这种方式节省时间。
在下面的代码中:
- 我创建一个
multiprocessing.Manager
以使我ls
可以在 2 个子进程之间共享。 - 然后我创建一个
multiprocessing.Pool
,希望创建两个进程。一个Process
做func()
,ls[0:100000]
另一个func()
做ls[100000:200000]
。 my_operation()
on的每个结果ls[index]
都是就地写入的。
示例代码(使用2 个进程):
from multiprocessing import Pool, Manager
# len(ls) = 200000
ls = ['a', 'b', ...]
# Each element of the scopes below is the scope to be processed by the process.
# (I want to use 2 processes in this example)
scopes = [ (0, 100000), (100000, 200000) ]
m = Manager()
ls = m.list(ls) # create a shared list for child processes
def func(range_start, range_end):
for index in range(range_start, range_end):
ls[index] = my_operation(ls[index])
def my_operation(str):
return str
with Pool(2) as pool:
pool.starmap_async(func, scopes)
pool.close()
pool.join()
问题
multiprocessing
用于处理此列表的不同范围时,在同一个列表上读取和写入是一个好主意吗?- 如何改进我的代码?(更改
Manager
为其他内容?较少的共享状态以及如何实现?...)
谢谢!
解决方案
推荐阅读
- kotlin - 如何避免手动检查列表中的类型?
- android - 使用 API 22 字符串更改设备中的应用程序语言不会更改
- flutter - Flutter (dart) 被 Sqflite 删除
- google-apps-script - 如何告诉谷歌表格只在特定时间段后进行计算?
- apache2 - CodeIgniter3 - 将应用程序作为 example.com/codeigniter 时,路由不起作用
- python - 进度条的奇怪行为
- python - 如何过滤模型中的对象以仅显示我的 ForeignKey 用户的对象?
- ftp - 为什么 WinSCP 看到远程文件没有更改/更新?
- r - 有没有办法识别数据框中小数位已移动的列?
- discord - 如何为不和谐机器人创建随机搜索查询