简体   繁体   English

Python-简单线程不会停止

[英]Python - Simple thread won't stop

I'm having a problem with a python script using threads. 我在使用线程的python脚本遇到问题。 I could mimic the problem with the following code: 我可以使用以下代码来模拟问题:

from threading import Thread

def func1():
    while True:
        print 'Function 1'

def main():
    t = Thread(target = func1)

    t.start()

    for i in xrange(100000):
        print 'Main'

    t.stop()

    print 'End'

if __name__ == '__main__':
    main()

The problem is when I interrupt the script with Ctrl + C or when it reaches its end, the thread running func1() won't stop. 问题是当我用Ctrl + C中断脚本或脚本结束时,运行func1()的线程不会停止。

I can only interrupt the execution if open the terminal and killall python . 如果打开终端并killall python我只能中断执行。

This is the first time I'm working with threads in Python. 这是我第一次使用Python处理线程。 What am I doing wrong? 我究竟做错了什么?

My approach (perhaps not the best, but it works) is: 我的方法(也许不是最好的方法,但是可行)是:

  1. Have a variable that the thread checks to see if it should stop. 有一个线程检查该变量是否应该停止的变量。
  2. Catch the ctrl-c in your main function. 将ctrl-c捕获到您的主要功能中。
  3. When caught, main function sets the variable that indicates the thread should stop. 捕获时,主函数设置指示线程应停止的变量。
  4. Main function calls join() on the thread to wait for it to finish. 主函数在线程上调用join()以等待其完成。
  5. Thread checks the variable, sees it is set, and returns (stops). 线程检查变量,看是否已设置,然后返回(停止)。
  6. The join() returns and you allow your main function to exit. join()返回并允许您的主要功能退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM