python事件同步线程threading.Event

threading.Event类内置了两个成员:
self._cond = Condition(Lock()) 这是一个条件同步线程,用于wait和noticeall
self._flag = False 这个值,默认是False,如果是False,线程进行到wait函数是会阻塞,如果是True,有wait函数的线程解除阻塞,并且在运行到wait函数时如果还是True,这个时候不会阻塞,所以一般在wait后的代码执行完成后,应紧跟event.clear()
threading.Event有4种方法:
Event.wait()
Event.set()
Event.clear()
Event.isSet()
set函数将self._flag值设置为True ,clear函数将self._flag值设置为False,isSet判断self._flag值是True还是False
import time
import threading
import sys

event = threading.Event()
action = 'parse'


class Plane(threading.Thread):
    def __init__(self, name, x, y):
        threading.Thread.__init__(self, name=name, args=(x, y))
        self.pix = [x, y]

    def run(self):
        global action
        while action != 'stop':
            event.wait()
            eval('.'.join(['self', action])+'()')
            sys.stdout.write(f'{self.name}:{self.pix}\n')
            event.clear()

    def left(self):
        self.pix[0] -= 1

    def right(self):
        self.pix[0] += 1

    def up(self):
        self.pix[1] -= 1

    def down(self):
        self.pix[1] += 1


if __name__ == '__main__':
    threads = []
    for i in range(1, 6):
        threads.append(Plane('Plane' + str(i), 100, 100))
    for t in threads:
        t.setDaemon(True)  # 设置子线程为守护,即主线程结束则跟着结束
        t.start()
    ipt = 'ok'
    print(ipt)
    while ipt != 'exit':
        ipt = input('请输入方向:')
        action = ipt.strip()
        if action in ['stop', 'left', 'right', 'up', 'down']:
            event.set()
        time.sleep(0.2)
    else:
        # action = 'stop'
        # event.set()
        print("完毕")

 

posted @ 2021-09-20 03:10  张永谊  阅读(628)  评论(0)    收藏  举报