简体   繁体   English

Python 代码使用多进程无限运行

[英]Python code using multiprocessing running infinitely

I am trying to execute the following code in jupyter notebook using multiprocessing but the loop is running infinitely.我正在尝试使用多处理在 jupyter notebook 中执行以下代码,但循环无限运行。
I need help resolving this issue.我需要帮助解决这个问题。

import multiprocessing as mp
import numpy as np

def square(x):
    return np.square(x)

x = np.arange(64)

pool = mp.Pool(4)
squared = pool.map(square, [x[16*i:16*i+16] for i in range(4)])

The output for mp.cpu_count() was 4. mp.cpu_count()的 output 是 4。

You need to rewrite your code to be something like:您需要将代码重写为:

def main():
    x = np.arange(64)
    pool = mp.Pool(4)
    squared = .....

if __name__ == '__main__':
    main()

This code is currently being run in every process.此代码当前正在每个进程中运行。 You need it to only run in the one process that is doing the setup.您需要它只在执行设置的一个进程中运行。

You forgot:你忘了:

pool.close()
pool.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM