【问题标题】:Terminate script with threads python使用线程 python 终止脚本
【发布时间】:2019-04-13 18:15:30
【问题描述】:

我有一些代码:

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 秒后终止 scipt。我尝试使用sys.exit 并使用psutil 终止进程。有谁知道如何终止它?我正在尝试:

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

并使用

watek.kill()

但它也不起作用。

【问题讨论】:

  • 不确定问题出在哪里,当您执行x=1 时,一旦x 变为1,您的线程就会终止。没有什么东西可以让线程保持活力。尝试在您的 for 循环中执行 f.isAlive(),您会看到线程已死?此外,没有必要用python-3python-2 标记这篇文章,它们都与python 使用相同的标记 - 这意味着它们会得到相同的关注,它只是帮助我们澄清我们使用哪种类型的代码'正在看/两个不同版本带来的挑战。因为你在做print timertime,它表示Python2,所以我删除了python-3
  • 请注意,仅将事件添加到您的 Thread 对象不会做任何有用的事情。线程中执行的代码必须实际检查并响应这样的终止标志。

标签: python python-2.7


【解决方案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?

这只是一个最小的示例(仍然不完整,但有效),它展示了如何创建在主程序执行时终止的线程的一般要点。

【讨论】:

  • 您可能只想将问题标记为重复,SO 上已经有大量此类解决方案。
  • @MisterMiyagi 没错,我做到了。发布我的答案后没有找到相关帖子,并且我已经将该帖子标记为“不清楚”,因为我并不完全认为问题足够清楚以理解问题 - 因为线程实际上并没有保持活力..呵呵。但你是 100% 正确的。
  • FWIW,您发布的解决方案是我尚未看到的解决方案。 ;)
猜你喜欢
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多