在Python中穿线:Parralel时循环
我正在尝试进行一个测试,其中两个时,真正的循环并排运行。
第一个循环打印“哈哈”,另一个应该打印“咖啡”。
但是看来代码被卡在第一个循环中,因此从未启动两个线程。
此处发布了类似的问题:,
但是解决方案似乎对我没有帮助。
这是代码段:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
thread1.join()
阻止主线程等待线程完成。但是它从来没有做到,因为它是,而true
循环。启动第二个线程后,您可以调用加入。另外,我不明白您为什么从
螺纹继承。Thread
,但我会以...编辑:删除
daemon = true true。
和.join()
由于所调用的功能是永无止境的。thread1.join()
blocks the main thread to wait for the thread to finish. But it never does since its awhile True
loop. You can call the join after starting the second thread.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.