'''
生产者与消费者模型(信号量解法)
acquire(),表示p操作,加1
release(),表示v操作,减1
'''
class FooBar:
def __init__(self, n):
self.n = n
self.p = threading.Semaphore(1)
self.v = threading.Semaphore(0)
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
self.p.acquire()
printFoo()
self.v.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
self.v.acquire()
printBar()
self.p.release()
三、交替打印字符串(不懂)
from threading import Semaphore
class FizzBuzz:
def __init__(self, n: int):
self.n = n
self.sem_fizz = Semaphore(0)
self.sem_buzz = Semaphore(0)
self.sem_fibu = Semaphore(0)
self.sem_num = Semaphore(1)
# printFizz() outputs "fizz"
def fizz(self, printFizz: 'Callable[[], None]') -> None:
for i in range(1, self.n+1):
if i % 3 == 0 and i % 5 != 0:
self.sem_fizz.acquire()
printFizz()
self.sem_num.release()
# printBuzz() outputs "buzz"
def buzz(self, printBuzz: 'Callable[[], None]') -> None:
for i in range(1, self.n+1):
if i % 3 != 0 and i % 5 == 0:
self.sem_buzz.acquire()
printBuzz()
self.sem_num.release()
# printFizzBuzz() outputs "fizzbuzz"
def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:
for i in range(1, self.n+1):
if i % 3 == 0 and i % 5 == 0:
self.sem_fibu.acquire()
printFizzBuzz()
self.sem_num.release()
# printNumber(x) outputs "x", where x is an integer.
def number(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n+1):
self.sem_num.acquire()
if i % 3 == 0 and i % 5 == 0:
self.sem_fibu.release()
elif i % 3 == 0:
self.sem_fizz.release()
elif i % 5 == 0:
self.sem_buzz.release()
else:
printNumber(i)
self.sem_num.release()