如何只停止线程,而程序应该在python中继续运行
您必须设置自己的停止线程的机制——Python没有内置的方法。这实际上是许多语言中的一个常见问题,不仅仅是Python如何只停止线程,而程序应该在python中继续运行,python,multithreading,Python,Multithreading,您必须设置自己的停止线程的机制——Python没有内置的方法。这实际上是许多语言中的一个常见问题,不仅仅是Python import time import threading class Check(threading.Thread): def __init__(self): self.stopped = False threading.Thread.__init__(self) def run(self): i = 0
import time
import threading
class Check(threading.Thread):
def __init__(self):
self.stopped = False
threading.Thread.__init__(self)
def run(self):
i = 0
while not self.stopped:
time.sleep(1)
i = i + 1
print(i)
if(i==5):
self.stopped = True
inst = Check()
inst.start()
这里我使用一个事件来表示线程是否应该停止。我们添加了一个stop方法来向事件发送信号,然后等待线程完成处理,然后再继续。这是非常简单的,但希望它能让你知道你可以采取什么样的策略。如果您想处理错误情况,例如如果
run()
方法中发生错误,或者run()
方法的主体花费的时间太长等,那么它会变得更加复杂。您需要正确格式化代码,以便它正好显示在StackOverflow上。选择代码块并单击花括号({}
),它会将其移动4个空格,以便正确显示。查看编辑面板下方的预览以查看最终结果。此处不欢迎仅限代码的问题。。。你应该读书。
import time
import threading
class Check(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# An event can be useful here, though a simple boolean works too since
# assignment is atomic in Python.
self.stop_event = threading.Event()
def run(self):
i = 0
while not self.stop_event.is_set():
time.sleep(1)
i = i + 1
print(i)
if(i==5):
self.stopped = True
def stop(self):
# Tell the thread to stop...
self.stop_event.set()
# Wait for the thread to stop
self.join()
inst = Check()
inst.start()
# Do stuff...
time.sleep(1)
inst.stop()
# Thread has stopped, but the main thread is still running...
print("I'm still here!")