如何在多个线程returns一个值之后继续程序流程?

How to continue the program flow after one of several threads returns a value?

在我的程序中,有一节我利用多线程来模拟分布式环境。所有线程都试图破解密码。如您所见,所有线程都使用不同的参数调用相同的目标函数 func。此函数 returns 每当 trial 找到破解密码的结果。

def func(self, inp):
    trial = 0
    while (crackPwd(inp, trial) != True):
        trial += 1
    return inp

threads = []

for inp in range(inpAmount):
    thr = threading.Thread(target=func, args=(inp))
    threads.append(thr)
    thr.start()

for thr in threads:
    thr.join()

但是我想做的是在其中一个线程破解密码后停止其他线程。我的意思是,我想在 func() 的线程 returns 之后继续程序流程。我试图找到解决方案,但 none 似乎符合我的问题。现在,我从所有线程中获得了结果,浪费了太多时间等待所有线程完成。我会感谢你的帮助。

你能使用一个线程实例吗Eventclass?

通过模拟代码中提到的 crackPwd 函数使其休眠直到 sleep_time 为 10 秒(概率为 10%)我测试了:

import time
import random
import threading

def crackPwd(inp, trial):
   sleep_time = random.randint(1, 10)
   time.sleep(sleep_time)
   return sleep_time

def func(inp):
   trial = 0
   while (crackPwd(inp, trial) != 10) and (not pwd_cracked.isSet()):
      trial += 1
   pwd_cracked.set()
   return inp

threads = []

for inp in range(10):
   pwd_cracked = threading.Event()
   thr = threading.Thread(target=func, args=(inp, ))
   threads.append(thr)
   thr.start()

for thr in threads:
   thr.join()

因此对于您的原始代码:

def func(self, inp):
    trial = 0
    while (crackPwd(inp, trial) != True) and (not pwd_cracked.isSet()):
        trial += 1
    pwd_cracked.set()
    return inp

threads = []

for inp in range(inpAmount):
    pwd_cracked = threading.Event()
    thr = threading.Thread(target=func, args=(inp, ))
    threads.append(thr)
    thr.start()

for thr in threads:
    thr.join()