线程没有终止

时间:2014-10-10 23:02:42

标签: python multithreading

有人可以告诉为什么线程没有在这里终止..

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()

1 个答案:

答案 0 :(得分:0)

您在主线程中调用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()