[PY3]——threading.Event

 

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》

posted @ 2017-09-26 09:24  Jelly_lyj  阅读(130)  评论(0编辑  收藏  举报