繁体   English   中英

为什么我没有进入 python3 的 while 循环?

[英]Why am I not reaching inside the while loop in python3?

我有以下代码作为 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

希望它对你有帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM