使用信号量交替打印foobar leetcode

获取信号量一定要放在print()语句的前面,释放信号量要放在print()语句的后面
在def foo()中,acquire放在了print()的后面,是因为acquire是为下一次循环获取信号量,是为了产生了一次错位。

import threading


class FooBar:
    def __init__(self, n):
        self.n = n
        self.s1 = threading.Semaphore(0)
        self.s2 = threading.Semaphore(0)

    def foo(self, printFoo: 'Callable[[], None]') -> None:

        for i in range(self.n):

            # printFoo() outputs "foo". Do not change or remove this line.
            printFoo()
            self.s1.release() # 输出完foo之后,可以让def bar获得信号量
            self.s2.acquire() 

    def bar(self, printBar: 'Callable[[], None]') -> None:

        for i in range(self.n):
            self.s1.acquire()
            # printBar() outputs "bar". Do not change or remove this line.
            printBar()
            self.s2.release() #输出完bar之后,可以让def foo获得信号量



Semaphores are a way of coordinating multiple threads of control, not
just for mutual exclusion. For example, a classical fixed-size
producer-consumer queue may use a semaphore initialized to a non-zero
value for producers so that they block when there are too many
elements in the buffer.

Semaphores manage a counter representing the number of release() calls minus
the number of acquire() calls, plus an initial value. The acquire() method
blocks if necessary until it can return without making the counter
negative. If not given, value defaults to 1.

你可能感兴趣的:(使用信号量交替打印foobar leetcode)