一旦找到目标,如何停止线程?

时间:2016-06-29 13:23:52

标签: python multithreading python-2.7 python-3.x

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

#!/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()

2 个答案:

答案 0 :(得分:1)

您无法简单地终止它们。但是你可以要求停止。请参阅示例:

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()

答案 1 :(得分:0)

您需要做的就是通过在启动之前将daemons属性设置为True 来创建线程对象daemon

默认值为False

,主程序线程结束时仍然运行的任何守护程序线程都会自动终止。

执行此操作的合理位置是在调用其构造函数之后:

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

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