python 线程间简单 event 通知

本例只建立了一个线程,实际上可以改为两个线程或者多个线程及多个事件。

  • t = threading.Thread(target=*func, args=(event_obj,)) 创建一个线程
  • event = threading.Event() 创建一个event
  • event.set()设置信号
  • event.clear()清除信号
  • event.wait()等待信号
    上代码
import threading
import time
count = 1
event1 = threading.Event()
event2 = threading.Event()
event1.clear()
event2.clear()

def do(event1,):
    global count
    print('Start thread')
    while True:
        try:
            event1.wait()
            print('Recieved event1.set() count:%d'%count)
            event1.clear()
            time.sleep(1)
            print('Set Event2')
            event2.set()
        except KeyboardInterrupt:
            print('Exit threading loop')
            break
            


t = threading.Thread(target=do, args=(event1,))
t.start()

def main_loop():
    global count
    while True:
        try:
            print('set     count:%d'%count)
            event1.set()
            event2.wait()
            print('Recieved event2.set()')
            time.sleep(1)
            count += 1
            event2.clear()
        except KeyboardInterrupt:
            print('Exit main loop')
            break

if __name__=="__main__":
    main_loop()       

参考文献:

  1. python多线程、锁、event事件机制的简单使用
  2. 【Python】threading.Event模块控制多线程
  3. Python多线程threading用法

你可能感兴趣的:(Python,python,threading,event,线程,事件)