gpt4 book ai didi

python - 找到目标后如何停止线程?

转载 作者:太空宇宙 更新时间:2023-11-03 16:24:43 24 4
gpt4 key购买 nike

所以我写了一个python,它将找到用户输入的pin,一切正常,除了一件事,那就是一旦找到pin,脚本将不存在。为什么我找到 pin 后就可以杀死所有其他线程?

#!/usr/bin/env python 
#
#
#
from threading import Thread
from random import randint
from time import sleep
from sys import exit
from os import system

system('clear');sleep(0.7)
Pin = int(raw_input('Enter a pin: '))


def Up():
global Pin
for pin in xrange(1111,10000):
system('clear')
print pin
if pin == Pin:
system('clear')
print 'U Pin Found: %d'%pin;sleep(0.7)
for i in range(3):
exit()


def Down():
global Pin
pins = xrange(10000)
for pin in reversed(pins):
system('clear')
print pin
if pin == Pin:
system('clear')
print 'D Pin Found: %d'%pin;sleep(0.7)
exit()



def Random():
global Pin

while True:
pins = randint(1111,10000)
print pins
if pins == Pin:
system('clear')
print 'R Pin Found: %d'%pins;sleep(0.7)
exit()


Task1 = Thread(target=Up,args=())
Task2 = Thread(target=Down,args=())
Task3 = Thread(target=Random,args=())


Task1.start()
Task2.start()
Task3.start()

最佳答案

你不能简单地终止它们。不过,您可以要求停止。请参阅示例:

from threading import Thread
from random import randint
from time import sleep
from sys import exit
from os import system

system('clear');sleep(0.7)
Pin = int(raw_input('Enter a pin: '))

terminateAll = false

def Up():
global Pin
for pin in xrange(1111,10000):
if terminateAll:
exit()
system('clear')
print pin
if pin == Pin:
terminateAll = true
system('clear')
print 'U Pin Found: %d'%pin;sleep(0.7)
for i in range(3):
exit()


def Down():
global Pin
pins = xrange(10000)
for pin in reversed(pins):
if terminateAll:
exit()
system('clear')
print pin
if pin == Pin:
terminateAll = true
system('clear')
print 'D Pin Found: %d'%pin;sleep(0.7)
exit()



def Random():
global Pin

while True:
if terminateAll:
exit()
pins = randint(1111,10000)
print pins
if pins == Pin:
terminateAll = true
system('clear')
print 'R Pin Found: %d'%pins;sleep(0.7)
exit()


Task1 = Thread(target=Up,args=())
Task2 = Thread(target=Down,args=())
Task3 = Thread(target=Random,args=())


Task1.start()
Task2.start()
Task3.start()

关于python - 找到目标后如何停止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38100921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com