【问题标题】:How to continue the program flow after one of several threads returns a value?几个线程之一返回值后如何继续程序流程?
【发布时间】:2021-07-06 13:07:19
【问题描述】:

在我的程序中,有一个部分我利用多个线程来模拟分布式环境。所有线程都在尝试破解密码。如您所见,所有线程都使用不同的参数调用相同的目标函数func。每当找到破解密码的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() 返回结果后继续执行程序流程。我试图找到一个解决方案,但它们似乎都不符合我的问题。现在,我得到了所有线程的结果,并且浪费了很多时间等待所有线程完成。感谢您的帮助。

【问题讨论】:

    标签: python python-3.x multithreading operating-system python-multithreading


    【解决方案1】:

    您可以使用线程Event 类的实例吗?

    通过模拟代码中提到的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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2020-10-10
      • 2020-11-14
      • 1970-01-01
      相关资源
      最近更新 更多