1. 程式人生 > >python 用threading中event來實現執行緒同步

python 用threading中event來實現執行緒同步

import threading
import time

event = threading.Event()
#event.clear():將event的標誌設定為False,呼叫wait方法的所有執行緒將被阻塞;
event.clear()


def synchro_fun():
    if not event.isSet(): # event.isSet():判斷event的標誌是否為True。
        #event.wait(timeout=None):呼叫該方法的執行緒會被阻塞,如果設定了timeout引數,超時後,執行緒會停止阻塞繼續執行
        event.
wait() print(time.time()) def main(): for i in range(6): t = threading.Thread(target=synchro_fun) t.setDaemon(False) t.start() print('start synchro') # event.set():將event的標誌設定為True,呼叫wait方法的所有執行緒將被喚醒; event.set() return 'over' if __name__ == '__main__'
: main()

輸出:

start synchro
1540958131.5454721
1540958131.5454721
1540958131.5454721
1540958131.5454721
1540958131.5454721
1540958131.5454721