[英]Python multiprocessing takes too long to complete after main process has finished
我试图让自己熟悉多处理,所以我使用蛮力搜索来查找字符串。
该脚本按预期工作,并且由于使用了迭代器 RAM 使用情况非常好。 我不明白的是在找到“密码”之后发生了什么。 脚本退出总是需要双倍的时间(在本例中,查找密码需要 70 秒,完成需要 160 秒),据我所知,它唯一需要做的就是终止所有进程。
这是正在发生的事情还是有其他事情?
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))
让您的getPassword
函数返回字符串(至少在成功的情况下)。 现在它总是返回默认的None
,所以result == userPass
永远不会是真的并且pool.terminate()
永远不会被执行。
此外,您可能希望使用更小的chunksize
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.