[PY3]——threading.Event

Jelly_lyj發表於2017-03-18

 

Class Event
{
    __init__(self)
    
    clear(self)
    
    is_set(self)
    
    set(self)
    
    wait(self,timeout=None)
    
}

 

is_set(self)

if and only if 內部標誌為真時返回Ture

wait(self,timeout=N)

如果內部標誌=Ture,立即返回
如果內部標誌=False,就阻塞(等待),直到另一個thread呼叫了set()方法,它的內部標誌變為了Ture
如果設定了timeout,則至多等待N秒時間

set(self)

將內部變數設定為True。所有等待它成真的執行緒都被喚醒(awake)了

clear(self)

將內部變數設定為False

 

class TestThread(threading.Thread):
    def __init__(self,name,event):
        super(TestThread,self).__init__()
        self.name=name
        self.event=event

    def run(self):
        logging.info("{} start".format(self.name))
        self.event.wait()
        logging.info("{} finished".format(self.name))

def main():
    event=threading.Event()

    threads=[]

    for i in range(1,4):
        threads.append(TestThread(str(i),event))

    logging.info("main thread start")

    event.clear()

    for thread in threads:
        thread.start()

    logging.info("sleep 5s...")
    time.sleep(5)
    logging.info("now awake other threads")
    event.set()

if __name__ == '__main__':
    main()

'''
19:43:50 [MainThread] main thread start
19:43:50 [1] 1 start
19:43:50 [2] 2 start
19:43:50 [3] 3 start
19:43:50 [MainThread] sleep 5s...
19:43:55 [MainThread] now awake other threads
19:43:55 [1] 1 finished
19:43:55 [2] 2 finished
19:43:55 [3] 3 finished
'''

 

class TestThread(threading.Thread):
    def __init__(self,name,event):
        super(TestThread,self).__init__()
        self.name=name
        self.event=event

    def run(self):
        logging.info("{} start".format(self.name))
        self.event.wait(5)
        logging.info("{} finished".format(self.name))

def main():
    event=threading.Event()

    threads=[]

    for i in range(1,4):
        threads.append(TestThread(str(i),event))

    logging.info("main thread start")

    event.clear()

    for thread in threads:
        thread.start()

    logging.info("sleep 10s...")
    time.sleep(10)
    logging.info("10s過去了")
    event.set()

if __name__ == '__main__':
    main()

'''
19:48:36 [MainThread] main thread start
19:48:36 [1] 1 start
19:48:36 [2] 2 start
19:48:36 [3] 3 start
19:48:36 [MainThread] sleep 10s...
19:48:41 [1] 1 finished
19:48:41 [2] 2 finished
19:48:41 [3] 3 finished
19:48:46 [MainThread] 10s過去了
'''

 

《Python:super沒那麼簡單》

《你不知道的super》

相關文章