在Python中穿线:Parralel时循环

发布于 2025-01-22 20:02:41 字数 944 浏览 4 评论 0原文

我正在尝试进行一个测试,其中两个时,真正的循环并排运行。

第一个循环打印“哈哈”,另一个应该打印“咖啡”。

但是看来代码被卡在第一个循环中,因此从未启动两个线程。


此处发布了类似的问题:

但是解决方案似乎对我没有帮助。


这是代码段:

def haha_function():
    while True:
        print("Haha")
        time.sleep(0.5)

def coffee_function():
    while True:
        print("Coffee")
        time.sleep(0.5)

class DummyScreen3(Screen, threading.Thread):

    def do_something(self):
        thread1 = threading.Thread(target=haha_function, daemon=True)
        thread1.start()
        thread1.join()

        thread2 = threading.Thread(target=coffee_function, daemon=True)
        thread2.start()
        thread2.join()

当函数do_something运行时,终端仅打印“哈哈”,而不是在“哈哈”和“咖啡”之间交替。

I'm trying to run a test where two while True loops are running side by side.

The first loop prints "Haha", the other is supposed to print "Coffee".

But it seems that the code gets stuck in the first loop, and thus never starts the two threads.


A similar issue was posted here: Python Threading: Multiple While True loops

But the solution doesn't seem to help me.


Here is the code snippet:

def haha_function():
    while True:
        print("Haha")
        time.sleep(0.5)

def coffee_function():
    while True:
        print("Coffee")
        time.sleep(0.5)

class DummyScreen3(Screen, threading.Thread):

    def do_something(self):
        thread1 = threading.Thread(target=haha_function, daemon=True)
        thread1.start()
        thread1.join()

        thread2 = threading.Thread(target=coffee_function, daemon=True)
        thread2.start()
        thread2.join()

When the function do_something is run, the terminal only prints "Haha", rather than alternating between "Haha" and "Coffee".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-小熊_ 2025-01-29 20:02:41

thread1.join()阻止主线程等待线程完成。但是它从来没有做到,因为它是,而true循环。启动第二个线程后,您可以调用加入。

class DummyScreen3(Screen, threading.Thread):

    def do_something(self):
        thread1 = threading.Thread(target=haha_function)
        thread1.start()

        thread2 = threading.Thread(target=coffee_function)
        thread2.start()

另外,我不明白您为什么从螺纹继承。Thread,但我会以...

编辑:删除daemon = true true。.join()由于所调用的功能是永无止境的。

thread1.join() blocks the main thread to wait for the thread to finish. But it never does since its a while True loop. You can call the join after starting the second thread.

class DummyScreen3(Screen, threading.Thread):

    def do_something(self):
        thread1 = threading.Thread(target=haha_function)
        thread1.start()

        thread2 = threading.Thread(target=coffee_function)
        thread2.start()

Also, I don't understand why you are inheriting from threading.Thread but I'll leave it as it is...

EDIT: Removed daemon=True and .join() since the functions called are never-ending.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文