首页 > 编程语言 > 详细

python事件同步线程threading.Event

时间:2022-05-27 23:27:54      阅读:37      评论:0      收藏:0      [点我收藏+]
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("完毕")

 

python事件同步线程threading.Event

原文:https://www.cnblogs.com/bohua320/p/15313453.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!