python - 为什么我没有进入 python3 的 while 循环?
问题描述
我有以下代码作为 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 < self.n,如 while 循环上方的 print 语句所示,while 循环内的 print 语句也不会打印。如何解决这个问题?
解决方案
你用什么代码来尝试运行你的程序?我试过了,我进入了 while 循环,但是其中有一个错误,也许这就是为什么它不会通过抛出一个你以前没有看到的错误来进入。
首先在您的 while 循环中,您print("bar " + self.barCount)
尝试将字符串与 int 连接,所以我建议您print("bar " + str(self.barCount))
改为
然后threading.Semaphore没有.locked()
方法所以也会报错,也许你应该这样搜索
最后一行有一个小错误self.semFoo += 1
,我想应该是self.fooCount += 1
希望它对你有帮助:)
推荐阅读
- css - 悬停动作移动文本。我如何解决它?
- c++ - 如何在另一个图像的开头关闭图像 - linux c ++
- .net - 如何仅将 Asp.Net Core Identity 与用户表一起使用
- angular - 离子滚动到虚拟滚动项目
- c# - 如何在 ComboBox (WindowsForm) 中启用 ctrl+c 快捷方式
- javascript - 我怎样才能按下元素键
- java - 无法在 rest api 中读取 InputStream 数据
- java - 设置唯一的 bean 名称 javax.management.InstanceAlreadyExistsException
- python - scikit-learn 中 MLPRegressor 的超参数优化
- reactjs - 向左浮动不在 sass 上工作