[英]python - how to run background thread without stopping main thread
这个简单的代码示例:
import threading
import time
class Monitor():
def __init__(self):
self.stop = False
self.blocked_emails = []
def start_monitor(self):
print("Run start_monitor")
rows = []
while not self.stop:
self.check_rows(rows)
print("inside while")
time.sleep(1)
def check_rows(self, rows):
print('check_rows')
def stop_monitoring(self):
print("Run stop_monitoring")
self.stop = True
if __name__ == '__main__':
monitor = Monitor()
b = threading.Thread(name='background_monitor', target=monitor.start_monitor())
b.start()
b.join()
for i in range(0, 10):
time.sleep(2)
print('Wait 2 sec.')
monitor.stop_monitoring()
如何在不阻塞主线程的情况下运行后台线程,在我的例子中是background_monitor
?
我想在调用stop_monitoring
之后停止background_monitor
线程
我的示例中,主线程的 for 循环从未调用过,后台一直在运行。
您当前的代码有两个问题。 首先,你在这条线上调用monitor.start_monitor
,而根据文档
target 是由 run() 方法调用的可调用对象 object。 默认为无,意味着什么都不叫
这意味着您需要将其作为 function 传递而不是调用它。 要解决此问题,您应该更改行
b = threading.Thread(name='background_monitor', target=monitor.start_monitor())
到
b = threading.Thread(name='background_monitor', target=monitor.start_monitor)
它将 function 作为参数传递。
其次,在停止线程之前使用b.join()
,它会等待第二个线程完成后再继续。 相反,您应该将其放在monitor.stop_monitoring()
下方。
更正后的代码如下所示:
import threading
import time
class Monitor():
def __init__(self):
self.stop = False
self.blocked_emails = []
def start_monitor(self):
print("Run start_monitor")
rows = []
while not self.stop:
self.check_rows(rows)
print("inside while")
time.sleep(1)
def check_rows(self, rows):
print('check_rows')
def stop_monitoring(self):
print("Run stop_monitoring")
self.stop = True
if __name__ == '__main__':
monitor = Monitor()
b = threading.Thread(name='background_monitor', target=monitor.start_monitor)
b.start()
for i in range(0, 10):
time.sleep(2)
print('Wait 2 sec.')
monitor.stop_monitoring()
b.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.