Power button alternately print FooBar

This question is to be noted that the order of two thread wakes up and waiting for the first thread should end earlier than the second thread, so if the first thread has ended, and the second thread is still waiting to be wake up, and that the second thread will wait forever, so the first thread wakes up after waiting first, so that he would wake up first and then the end of the second thread

  • Incoherent, direct look at the code it
from threading import Condition, Thread
import time


def printFoo():
    print('foo', end='')
    time.sleep(0.5)


def printBar():
    print('bar', end='')
    time.sleep(0.5)


class FooBar:
    def __init__(self, n):
        self.n = n
        self._lock = Condition()


    def foo(self, printFoo) -> None:
        self._lock.acquire()
        for i in range(self.n):
            printFoo()
            # 这里要先等待
            self._lock.wait()
            self._lock.notify_all()
        self._lock.release()


    def bar(self, printBar) -> None:
        self._lock.acquire()
        for i in range(self.n):
            printBar()
            # 这里要先唤醒其他线程,
            self._lock.notify_all()
            self._lock.wait()
        self._lock.release()

if __name__ == '__main__':
    n = 10
    foobar = FooBar(n)
    t1 = Thread(target=foobar.foo, args=(printFoo,))
    t2 = Thread(target=foobar.bar, args=(printBar,))
    # t2.start()
    t1.start()
    t2.start()

When execution: 132 ms, beat all Python3 submission of 85.39% of user
memory consumption: 16.1 MB, defeated 100.00% of users in all Python3 submission

Published 62 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/zjbyough/article/details/99102058