简体   繁体   English

主进程完成后,Python 多处理需要很长时间才能完成

[英]Python multiprocessing takes too long to complete after main process has finished

I'm trying to familiarize myself with multiprocessing so I used a brute force search to find a string.我试图让自己熟悉多处理,所以我使用蛮力搜索来查找字符串。

The script works as expected and due to the use of an iterator RAM usage is pretty good.该脚本按预期工作,并且由于使用了迭代器 RAM 使用情况非常好。 What I don't understand is what is happening after the "password" has been found.我不明白的是在找到“密码”之后发生了什么。 It always takes double the time for the script to exit (in this example 70sec for finding the password and 160sec to complete) where, as far as I understand, the only thing it still has to do is terminate all the processes.脚本退出总是需要双倍的时间(在本例中,查找密码需要 70 秒,完成需要 160 秒),据我所知,它唯一需要做的就是终止所有进程。

Is this what is happening or there is something else?这是正在发生的事情还是有其他事情?

import itertools
import multiprocessing as mp
import string
import time

# start timer
tStart = time.time()

userPass = 'mypass'

def getPassword(passList):
    str = ''.join(passList)
    if userPass == str:
        print('\n')
        print('~~~ CRACKED ~~~')
        print('User password is {}'.format(str))
        print('Cracked password in {:.3f} seconds'.format(time.time() - tStart))

if __name__ == '__main__':
    # possible characters used in password
    chars = list(string.ascii_lowercase)    

    # get all character combinations
    allPasswords = itertools.product(chars, repeat=len(userPass))

    # calculate optimum chunk number
    totalComb = len(chars) ** len(userPass)
    nChunks = int(max(1, divmod(totalComb, mp.cpu_count() * 4)[0]))

    with mp.Pool(processes=mp.cpu_count()) as pool:
        for result in pool.imap_unordered(getPassword, allPasswords, chunksize=nChunks):
            if result == userPass:
                pool.terminate()
                break
            del result # trying to reduce memory usage
    tEnd = time.time()
    tElapsed = tEnd - tStart

    print('Total elapsed time {:.3f} seconds'.format(tElapsed))

Make your getPassword function return the string (at least in the success case).让您的getPassword函数返回字符串(至少在成功的情况下)。 Right now it always returns the default None , so result == userPass is never true and pool.terminate() is never executed.现在它总是返回默认的None ,所以result == userPass永远不会是真的并且pool.terminate()永远不会被执行。

Also, you might want to use a much smaller chunksize .此外,您可能希望使用更小的chunksize

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

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