Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何正确停止python线程?_Python_Multithreading - Fatal编程技术网

如何正确停止python线程?

如何正确停止python线程?,python,multithreading,Python,Multithreading,我是Python新手。这是我的代码: import logging logging.basicConfig(level = logging.DEBUG, format = "[%(levelname)s] (%(threadName)-10s) %(message)s") import threading import time def thread1(): for i in range(0, 10, 2): logging.debug(i) time.

我是Python新手。这是我的代码:

import logging
logging.basicConfig(level = logging.DEBUG, format = "[%(levelname)s] (%(threadName)-10s) %(message)s")
import threading
import time

def thread1():
    for i in range(0, 10, 2):
        logging.debug(i)
        time.sleep(1)


def thread2():
    for i in range(10, 20):
        logging.debug(i)
        time.sleep(1)

t1 = threading.Thread(name = "thread1", target = thread1)
t1.setDaemon(True)
t1.start()

t2 = threading.Thread(name = "thread2", target = thread2)
t2.setDaemon(True)
t2.start()
当我复制代码并将其粘贴到python命令行提示符中时,得到了以下结果

如您所见,这两个线程已经完成,但程序似乎没有退出(我没有得到命令提示符)。我认为这与我没有结束线程的代码有关。这是真的吗?如何解决此问题?
谢谢。

实际上,命令提示符在第
>>[DEBUG](thread1)2行返回,并准备好进行更多输入。执事线程在后台运行,打印他们应该打印的内容,并最终完成。您根本不需要键入ctrl-c。您可能刚刚输入了另一个python命令。

如果我没记错的话——您需要使用threading.Event来停止线程。例如:

self.stoprequest = threading.Event()

""" When self.stoprequest.set() is called,
it sets an event on the thread - stopping it.""" 
self.stoprequest.set()
因此,如果在启动的每个线程上创建threading.Event(),则可以使用instance.set()从外部停止它


您还可以终止生成子线程的主线程:)

请参阅我的问题答案。如果您只需要在主程序线程中调用
thread\u 1.join()
。setDaemon()已弃用,请使用thread.daemon=True(或在创建线程时将其作为关键字arg传递)。看医生:不是真的。线程没有标准的退出方式。您可以实现某种命令结构,比如Event,但它只有在线程被编码为使用它时才起作用。另一个例子是队列和线程代码识别为终止的特殊消息。不正确。除非目标线程定期检查stoprequest,或者对该特定事件阻塞
wait
ing,否则设置该事件不会起任何作用。在python中终止(非守护进程)线程的唯一可靠方法是线程本身检测何时停止并执行此操作。你可以使用
threading.Event
对象作为实现这一点的一种方法,但它们的关键是线程需要合作。你完全正确,我的回答不够全面。我过去的经验是使用while(threading\u event.is\u set())-作为无法停止的线程。当其run()方法终止时,它将停止活动–正常情况下,或者引发未处理的异常。哇,这正是问题所在!非常感谢你指出这一点。