如何在一段时间后终止python中的线程?

时间:2015-12-29 03:01:40

标签: python multithreading

我有多个运行while循环的线程。我想在一段时间后终止这些线程。我知道其他类似的问题,但我不知道如何将这些答案转移到我的代码中。

 def function1(arg1, arg2, arg3, duration):
        t_end = time.time() + duration
        while time.time() < t_end:
            #do some stuff

for i in range(100):
    t = Thread(target = function1, args=(arg1, arg2, arg3, 10))
    t.start()

这会打开100个线程,但它们永远不会关闭。如何在指定时间后关闭这些线程,在此示例中为10秒?我的函数打开一个套接字。

2 个答案:

答案 0 :(得分:1)

使用终止线程的混合(此处的信息:Is there any way to kill a Thread in Python?

和线程计时器对象:https://docs.python.org/2/library/threading.html#timer-objects

下面的代码对我有用,但它不断抛出TypeError的事实让我感到困惑。我似乎无法找到有关它为何发生的原因或如何防止它的信息:

threadingtest.py

#!/usr/bin/env python3
import time
import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()
        try:
            self.join()

        except TypeError as tE:
            print("Shutting down")

    def stopped(self):
        return self._stop.isSet()

class MyStoppableThread(StoppableThread):

    def __init__(self, *args):
        super(MyStoppableThread, self).__init__()
        self.args = args # Use these in the thread

    def run(self):
        print("Started my thread with arguments {}".format(self.args))
        while not self.stopped():
            time.sleep(1)
            # THIS IS WHERE YOU DO THINGS

if __name__ == "__main__":
    threads = []
    for i in range(100):
        t = MyStoppableThread(i, 'a', 'b', 'c')
        t.start()
        threads.append(t)

    print("\n:: all threads created\n")
    time.sleep(5)
    print("\n:: killing all threads\n");
    for t in threads:
        t.stop()

答案 1 :(得分:1)

您可以将回调传递给每个线程。并创建一个线程列表。

threadlist  = {}
def cb(id, currtime):
    t = threadlist[id]
    d = currtime - t.starttime
    if d > 10:
        return True
    else:
        return False

def function1(arg1, arg2, arg3, duration, cb, threadid):
    t_end = time.time() + duration
    while time.time() < t_end:
        #do some stuff
        if cb(threadid, time.time()):
            break

for i in range(100):
    t = Thread(target = function1, args=(arg1, arg2, arg3, 10, cb, i))
    threadlist[id] = {"starttime": time.time(), "thread": t}
    t.start()

并检查:

time.sleep(15)
for item in threadlist.values():
    print(item.thread.is_alive())