有没有办法在找到正确答案时停止Python线程?

时间:2014-05-27 23:07:53

标签: python multithreading

我正在尝试检查这样的答案列表:

def checkAns(File, answer):
    answer = bytes(answer, "UTF-8")
    try:
        File.extractall(pwd=answer)
    except:
        pass
    else:
        print("[+] Correct Answer: " + answer.decode("UTF-8") + "\n")

def main():
    File = zipfile.ZipFile("questions.zip")
    ansFile = open("answers.txt")
    for line in ansFile.readlines():
        answer = line.strip("\n")
        t = Thread(target=extractFile, args=(File, answer))
        t.start()

假设正确答案为4,您的列表包含值1到1000000。 如何在达到4之后停止并且不通过列表中的剩余数字?

我尝试了几种不同的方式:

else:
    print("[+] Correct Answer: " + answer.decode("UTF-8") + "\n")
        exit(0)

以及

try:
    File.extractall(pwd=answer)
        print("[+] Correct Answer: " + answer.decode("UTF-8") + "\n")
        exit(0)
except:
        pass

如何在找到正确答案后让所有线程停止?

1 个答案:

答案 0 :(得分:0)

奇怪的是,在Python中你无法杀死线程:

  

Python的Thread类支持Java的一部分行为   线程类;目前,没有优先级,没有线程组,   并且线程不能销毁,停止,暂停,恢复或   中断。

https://docs.python.org/2/library/threading.html#threading.ThreadError

此示例创建一个将运行10秒的线程。然后父母等待一秒钟,然后完成",并等待(即:join() s)未完成的线程,然后干净地离开。

import sys, threading, time

class MyThread(threading.Thread):
    def run(self):
        for _ in range(10):
            print 'ding'
            time.sleep(1)

MyThread().start()

time.sleep(2)

print 'joining threads'
for thread in threading.enumerate():
    if thread is not threading.current_thread():
        thread.join()
print 'done'