【问题标题】:Why am I not reaching inside the while loop in python3?为什么我没有进入 python3 的 while 循环?
【发布时间】: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


【解决方案1】:

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

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

那么threading.Semaphore没有.locked()方法所以也会抛出错误,或许你应该这样搜索

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

希望对你有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多