简体   繁体   English

python中的多处理不会停止运行

[英]multiprocessing in python does not stop running

I tried a simple example of multiprocessing in python from their website itself, but it does not give any input.我从他们的网站上尝试了一个在 python 中进行多处理的简单示例,但它没有提供任何输入。 It's showing as running itself and I am not able to stop it in jupyter notebook.它显示为正在运行,我无法在 jupyter notebook 中停止它。

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    p = Pool(5)
    print(p.map(f, [1, 2, 3]))

It's the same for other multiprocessing examples too.其他多处理示例也是如此。 It does not give any error or timeout or anything.它不会给出任何错误或超时或任何东西。 It's like it is in an infinite loop or deadlock.这就像处于无限循环或死锁中。

I'm also on Windows.我也在 Windows 上。

  1. As pointed out 'from multiprocessing.pool import ThreadPool as Pool' works.正如所指出的,'from multiprocessing.pool import ThreadPool as Pool' 有效。
  2. also you need to add if name == ' main ':您还需要添加 if name == ' main ':
  3. also below that you need to add : 'with Pool(4) as pool:'在下面还需要添加:'with Pool(4) as pool:'

example例子

from multiprocessing.pool import ThreadPool as Pool
from os import getpid
import time
import pandas as pd


pyfiles = [10,2,3,5]    

def scraper(x):
    results_df = pd.DataFrame({})
    print('Program started:',x,"I'm process", getpid())
    time.sleep(x)
    print('Program completed:',x)
    results_df.to_csv('multi{}.csv'.format(x))


if __name__ == '__main__':
    with Pool(4) as pool:
        start=time.time()
        result = pool.map(scraper, pyfiles)
        pool.terminate()
        pool.join()
        print("Time Taken: ",str(time.time()-start))

I dont know how but it worked when i imported like given below.我不知道如何但是当我像下面给出的那样导入时它起作用了。

from multiprocessing.pool import ThreadPool as Pool

The problem was with pool in importing multiprocessing.问题在于导入多处理时的池。

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

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