Python threading Event類實現事件的對象(對子線程的事件管理)

原因:主線程要控制其他線程的執行
注意:event.wait(timeout) 要設置超時時間【看註釋哦】,可以理解一下守護線程。

# coding=utf-8
import logging
import threading
import time
from threading import Event

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [*] %(threadName)s %(message)s"
)
threads = []
event = Event()


def test (event):
    # 1.準備中---------------------------------------------
    while not event.isSet():
        logging.info(f" is ready")
        time.sleep(1)
    # 2.等待通知------------------------------------------
    event.wait(0.1)  # daemon=True設置守護線程,0.1秒後隨着主線程退出
    # 3.運行中--------------------------------------------
    while event.isSet():
        logging.info(f" is running")
        time.sleep(1)


def main ():
    logging.info("------ 主線程開始 --------")
    # 2個線程
    for i in range(2):
        threads.append(threading.Thread(target=test, args=(event,), daemon=True))
    # 阻塞啓動線程---------------------------
    for t in threads:
        t.start()
    # 這裏就不要了,因爲會阻塞主線程
    # for t in threads:
    #     t.join()
    time.sleep(3)
    logging.info("-------------- event is set")
    event.set()
    time.sleep(3)
    logging.info("------------ event is clear")
    event.clear()
    logging.info("------- 主線程結束 --------")


if __name__ == '__main__':
    main()

輸出:

2019-10-02 18:25:15,171 [*] MainThread ------ 主線程開始 --------
2019-10-02 18:25:15,172 [*] Thread-1  is ready
2019-10-02 18:25:15,172 [*] Thread-2  is ready
2019-10-02 18:25:16,173 [*] Thread-2  is ready
2019-10-02 18:25:16,173 [*] Thread-1  is ready
2019-10-02 18:25:17,174 [*] Thread-1  is ready
2019-10-02 18:25:17,174 [*] Thread-2  is ready
2019-10-02 18:25:18,173 [*] MainThread -------------- event is set
2019-10-02 18:25:18,176 [*] Thread-2  is running
2019-10-02 18:25:18,176 [*] Thread-1  is running
2019-10-02 18:25:19,176 [*] Thread-2  is running
2019-10-02 18:25:19,178 [*] Thread-1  is running
2019-10-02 18:25:20,178 [*] Thread-2  is running
2019-10-02 18:25:20,178 [*] Thread-1  is running
2019-10-02 18:25:21,173 [*] MainThread ------------ event is clear
2019-10-02 18:25:21,173 [*] MainThread ------- 主線程結束 --------
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章