【发布时间】:2021-08-20 08:38:58
【问题描述】:
我有以下代码尝试解决 leetcode https://leetcode.com/problems/print-foobar-alternately 问题:
from threading import Semaphore
class FooBar:
def __init__(self, n):
self.n = n
self.semFoo = []
for i in range(n):
self.semFoo.append(Semaphore(0))
self.semBar = []
for i in range(n):
self.semBar.append(Semaphore(0))
self.fooCount = 0
self.barCount = 0
print("releasing semFoo[0]")
self.semFoo[0].release()
def foo(self, printFoo: 'Callable[[], None]') -> None:
print("fooCount is " + str(self.fooCount) + " " + str(self.n))
while self.fooCount < self.n:
print("foocount is" + self.fooCount)
if not self.semFoo[self.fooCount].locked():
print("foo " + self.fooCount)
printFoo()
self.semBar[self.barCount].release()
self.barCount += 1
def bar(self, printBar: 'Callable[[], None]') -> None:
print("barCount is " + str(self.barCount) + " " + str(self.n))
while self.barCount < self.n:
with self.semBar[self.barCount]:
print("bar " + self.barCount)
printBar()
self.semFoo[self.semFoo].release()
self.semFoo += 1
这个想法是创建两个信号量列表并交替释放这些信号量。但是,foo 和 bar 的 while 循环内的任何代码都没有被执行。即使 self.fooCount
【问题讨论】:
-
首先你在 print("foocount is" + self.fooCount) 字符串中连接整数。您有三个错误的打印件。另外如果你做 dir(Semaphore) 你不会找到locked() 方法。
标签: python python-3.x while-loop semaphore