Python threading Event类实现事件的对象(对子线程的事件管理)

mac2022-06-30  26

原因:主线程要控制其他线程的执行 注意: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 ------- 主线程结束 --------
最新回复(0)