[英]Thread is not terminating
有人可以说为什么线程不在这里终止。
import sys, threading, select
class MyMaster(threading.Thread):
def __init__(self, event_stop):
super(MyMaster, self).__init__(name='MyMaster')
self.event_stop = event_stop
def run(self):
#waiting for user keyboard Interrupt
while not (self.event_stop.isSet():
#Avoiding wait forever condition
if sys.stdin in select.select([sys.stdin],[], [],0):
ch = sys.stdin.read(1)
#print "you have entered : ", repr(ch)
if ch == 'a':
#do stuff
elif ch == 'h':
#do stuff
elif ch == 'p':
#do stuff
elif ch == 'r':
#do stuff
else:
print "breaking..........................................."
break
print "done"
def stop(self):
self.event_stop.set()
try:
event_stop = threading.Event()
# Creating Master
master = MyMaster(event_stop)
master.start()
event_stop.wait()
master.stop()
print threading.enumerate()
except:
traceback.print_exc()
您正在主线程中调用event_stop.wait()
,它将阻塞直到其他线程出现并调用event_stop.set()
。 但是,没有其他线程可以执行此操作-主线程最终应该通过调用master.stop()
来执行此操作,但要等到下一行永远无法到达时才执行。 您可以通过简单地删除event_stop.wait()
调用来解决此问题:
event_stop = threading.Event()
# Creating Master
master = MyMaster(event_stop)
master.start()
time.sleep(2) # Use this to delay a bit, if that's what you were going for
master.stop()
print threading.enumerate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.