[英]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: 我的方法(也许不是最好的方法,但是可行)是:
join()
on the thread to wait for it to finish. 主函数在线程上调用join()
以等待其完成。 join()
returns and you allow your main function to exit. join()
返回并允许您的主要功能退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.