关于Python线程的Event事件机制

先看官方的Event类注解:

class Event:
    """Class implementing event objects.
    Events manage a flag that can be set to true with the set() method and reset
    to false with the clear() method. The wait() method blocks until the flag is
    true.  The flag is initially false.

    """

    # After Tim Peters' event class (without is_posted())
    def __init__(self):
        self._cond = Condition(Lock())
        self._flag = False

    ...

注解中说明了3个可以使用的方法:set()、wait()、clear()。

set():设置标志位为True。(Set the internal flag to true.)

wait():如果当前标志位是False,则进入阻塞状态,直到标志位变为True,解除阻塞,该方法立即返回。(Block until the internal flag is true.)

clear():设置标志位为False。(Reset the internal flag to false.)

 

这3个方法都需要用到,我一开始在项目中忽略了clear(),导致线程无法进入休眠状态,一直在运行。

下面是正确使用的demo,生产者产生一个数字,消费者读取这个数字,并打印,进行10次:

from threading import Thread, Event
import time

x = 0

class Producer(Thread):
    def __init__(self, consumer):
        Thread.__init__(self)
        self.consumer = consumer

    def run(self):
        global x
        for i in range(0, 10):
            x = i**2
            self.consumer.wake()
            time.sleep(1)

class Consumer(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.event = Event()

    def wake(self):
        # 设置标志位(置为True)
        self.event.set()

    def run(self):
        global x
        count = 10
        while count > 0:
            # 阻塞等待直到标志位被置为True
            self.event.wait()
            # 清除标志位(置为False),为下次阻塞等待做准备
            self.event.clear()
            print('Consumer:', time.time(), 'x=', x)
            count -= 1

if __name__ == '__main__':
    c = Consumer()
    c.start()
    Producer(c).start()

测试结果:

Consumer: 1585116237.4874198 x= 0
Consumer: 1585116238.4887447 x= 1
Consumer: 1585116239.4891763 x= 4
Consumer: 1585116240.4904392 x= 9
Consumer: 1585116241.4907174 x= 16
Consumer: 1585116242.4911718 x= 25
Consumer: 1585116243.4913554 x= 36
Consumer: 1585116244.4918528 x= 49
Consumer: 1585116245.492998 x= 64
Consumer: 1585116246.4934428 x= 81

Process finished with exit code 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章