使用线程python

时间:2018-11-10 10:53:27

标签: python python-2.7

我有一些代码:

red = "\033[1;31m"
green = "\033[1;32m"
yellow = "\033[1;33m"
blue = "\033[1;34m"
defaultcolor = "\033[0m"

class watek(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        x=1 

def timer(stopon):
    timertime = 0
    while True:
        time.sleep(1)
        timertime += 1
        print timertime
        if timertime == stopon:
            killpro()
def killpro():
    sys.exit()

threadsyy = []

threadsamount = 300
i = 1
while i <= threadsamount:
    thread = watek()
    threadsyy.append(thread)
    i += 1
    print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + '\n')

a = 0
for f in threadsyy:
    f.start()
    a += 1
    #print "Thread work " + str(a)
timer(5)

我需要在5秒钟后终止密码。我尝试使用sys.exit,并使用psutil终止进程。有人知道如何终止吗?我正在尝试:

class watek(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._kill = threading.Event()

并使用

watek.kill()

但它也不起作用。

1 个答案:

答案 0 :(得分:1)

这不会解决您的问题,但是如果有人从搜索引擎中寻找线程在实际上仍然存活的末端线程时,我会把它留在这里。

class worker(threading.Thread):
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self)

    def run(self):
        main_thread = None
        for thread in threading.enumerate():
            if thread.name == 'MainThread':
                main_thread = thread
                break

        while main_thread and main_thread.isAlive():
            #do_work()
            print('Thread alive')
            time.sleep(1)

# I'll keep some of the analogy from above here:
threads = []
thread = worker()
threads.append(thread)

for f in threads:
    f.start()

time.sleep(5)

for f in threads:
    print('Is thread alive:', f.isAlive())

该程序将在打印后大约5秒钟后退出,如果线程还活着(它们将会是),则在打印后立即退出,但是这些线程将查找主进程状态,如果主线程退出,则终止线模。

这是一种创建线程的方法,该线程将在主程序运行时结束。
在实践中,问题更大,您必须确保它们能很好地终止并自行清理。还有f.join()会等待线程终止,可以在这里找到很好的解释:what is the use of join() in python threading

还向线程发出了退出的信号,对此也进行了详尽的讨论,此处是一个很好的示例:How to stop a looping thread in Python?

这只是一个最小的示例(仍然不完整,但可以正常工作),该示例显示了如何创建在主程序执行时终止的线程的一般要旨。