python事件同步线程threading.Event
2021/9/20 9:05:12
本文主要是介绍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 != 's': event.wait() if action == 'l': self.left() elif action == 'r': self.right() elif action == 'u': self.up() elif action == 'd': self.down() event.clear() def left(self): self.pix[0] -= 1 sys.stdout.write(f'{self.name}:{self.pix}\n') def right(self): self.pix[0] += 1 sys.stdout.write(f'{self.name}:{self.pix}\n') def up(self): self.pix[1] -= 1 sys.stdout.write(f'{self.name}:{self.pix}\n') def down(self): self.pix[1] += 1 sys.stdout.write(f'{self.name}:{self.pix}\n') 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() event.set() time.sleep(0.2) else: action = 's' # event.set() print("完毕")
这篇关于python事件同步线程threading.Event的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型