簡體   English   中英

線程沒有終止

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM