python - python 3.X windows 多处理
问题描述
我已经阅读了许多关于窗口和 linux 多处理之间差异的主题,但我仍然找不到答案。我有这样的脚本:
def create_file():
#here user define output file name
def READ_MANY_LOG():
#here user define path to log files and we read all these logs to one list()
def select_unic_value(READ_MANY_LOG):
#here specified unic value selected
def SEARCH_ENGINE(search_criteria, READ_MANY_LOG):
#here perform search from all logs with search_criteria and stored to multiprocess dict (return_dict)
def sort_all_logs_per_unic_value(create_file, select_unic_value):
mpc = 0
mpa = []
for n in select_unic_value:
search_criteria = criteria(n)
mps = Process(target=SEARCH_ENGINE, args=(search_criteria, READ_MANY_LOG))
mpa.append(mps)
mpc = mpc + 1
if mpc>=multiprocess.cpu_count():
for p in mpa:
p.start()
for p in mpa:
p.join()
For t_g in return_dict.values():
for t_x in t_g:
print(t_x,file=out, flush=True, end='')
print('PRINT done')
mpc = 0
mpa = []
return_dict = multiprocess.Manager().dict()
create_file()
READ_MANY_LOG()
select_unic_value(READ_MANY_LOG)
if __name__ == "__main__":
MULT.freeze_support()
SORT_BY_MAC_DIR(output_name)
它在 linux 上完美运行,因为多进程从 create_file()
,继承值READ_MANY_LOG()
,
select_unic_value(READ_MANY_LOG)
并且仅针对SEARCH_ENGINE
. 但是在 Windows 上,因为 spawn 它会在不同的进程中启动整个脚本。Windows 有没有办法仅针对特定部分启动多进程:SEARCH_ENGINE
?提前非常感谢。
解决方案
在 linux 和 windows 中,多进程都会产生一个新进程。这在您的脚本需要专门访问 cpu 或核心(也称为受 cpu 绑定)的情况下非常有用。顺便说一句,您的应用程序看起来像是受磁盘限制的——因此使用线程可能会更好。
在您的脚本场景中,您需要一种方法让父进程在所有进程之间整理或共享值。这包括调用进程和启动的所有子进程。
可以使用进程池来完成整理。例如,为您的流程创建一组日志以供处理。然后在最后加入结果。
from multiprocessing import Pool
def SEARCH_ENGINE((sc, logs)):
# Do something with sc and logs
return myvalue
if __name__ == '__main__':
p = Pool(5)
# results will be a list of return values for each tuple listed
results = p.map(, [("First Search", "file1"), ("Second Search, ...)])
或者,您可以使用multiprocessing.Value
或使用共享内存multiprocessing.Array
,但是当您需要使用时,这会变得有点复杂ctypes
。
推荐阅读
- python - 使用 python seaborn 仅在某些值之间设置热图相关性
- python - Python Pandas 中 DataFrame 中从日期计算 od 天数的问题
- java - java 8中映射后如何返回可选值
- java - 反序列化时如何根据父类强制类型类中的字段
- jmeter - 我们可以将 HTTP 缓存管理器用于 REST API 负载运行吗
- php - 如何让 Laravel 8 会话在 Heroku 上运行?由于它们没有正确保存
- java - 如何将我的 Docker 应用程序连接到远程数据库?
- python - 在 mac 上不起作用 python curses 的 getstr()
- javascript - webdriverio中单个断言中的多个值
- javascript - 使用 JavaScript 检查瑞士电话号码