Python 多处理循环

标签 python multithreading multiprocessing data-processing data-ingestion

我希望使用多处理来加速缓慢的循环。然而,从我所看到的多处理示例来看,我不确定这种实现是否是良好的实践、可行或可能。

循环大致分为两个部分:数据摄取数据处理。我希望在处理过程中开始数据摄取的下一部分,以便数据尽快可用。

伪代码:

d = get_data(n)
for n in range(N):
    p = process_data(d)
    d = get_data(n+1) #prepare data for next process loop
  1. 多重处理适合这种功能吗?
  2. 如何做到这一点?

提前致谢。

最佳答案

正如您所说,多处理基本上是调度和收集工作。 正如您所澄清的,您基本上希望 process_dataget_data 并行工作。

这是我为您提供的解决方案

import multiprocessing as mp

# create pool for dispatching work
pool = mp.Pool()

# call your functions asynchronously
process_data_process = pool.apply_async(process_data, (d,))
get_data_process = pool.apply_async(get_data, (n+1,))

# After your functions are dispatched, wait for results
process_data_result = process_data_process.get()
get_data_result = get_data_process.get()

# Note: get_data_result will not be fetched till process_data_result is ready
# But that should be fine since you can't start the next batch
# till this batch is done

你可以将其包装在你的循环中。 希望这能回答您的问题!

关于Python 多处理循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778842/

相关文章:

python - 无法在Mac上导入Pyodbc

python - "np.cumsum() like"- 根据实际值迭代

c++ - 提供 QtConcurrent 功能的通用 C++ 库?

multithreading - 使用 TThread.Resume 有什么问题?

c# - 当另一个完成使用多线程时启动一个方法

python - 对于这个例子,为什么颜色在 matplotlib 中不起作用?

python - Python中浅拷贝而不是新对象

Python 多处理错误 : AttributeError: module '__main__' has no attribute '__spec__'

python - 多线程与多处理 : Which one to select?

python - 使用 Xarray 和 Numpy 数组进行多处理