首页 > 解决方案 > 为什么我没有进入 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 语句也不会打印。如何解决这个问题?

标签: pythonpython-3.xwhile-loopsemaphore

解决方案


你用什么代码来尝试运行你的程序?我试过了,我进入了 while 循环,但是其中有一个错误,也许这就是为什么它不会通过抛出一个你以前没有看到的错误来进入。

首先在您的 while 循环中,您print("bar " + self.barCount)尝试将字符串与 int 连接,所以我建议您print("bar " + str(self.barCount))改为

然后threading.Semaphore没有.locked()方法所以也会报错,也许你应该这样搜索

最后一行有一个小错误self.semFoo += 1,我想应该是self.fooCount += 1

希望它对你有帮助:)


推荐阅读