gpt4 book ai didi

Python线程在1个循环后卡住

转载 作者:太空宇宙 更新时间:2023-11-04 04:53:26 24 4
gpt4 key购买 nike

使用 python 3 处理一些线程,同时运行两个东西。这是我用来测试的脚本。

from threading import Thread
import time as t
x=1
z=1
var=0
def firstFunction():
global var
while x == 1:

var += 1
t.sleep(1)
def secondFunction():

while z == 1:
print(var)
t.sleep(1)
add=Thread(target=firstFunction)
see=Thread(target=secondFunction)
add.start()
see.start()

出于某种原因,当我运行它时,您希望它进行计数,对吗?但它只是说

1

并没有结束或说错误,但如果我尝试一个脚本,该脚本询问您是否想查看 var,它工作正常。有什么办法可以让我在没有询问的情况下工作吗?这是带有询问的代码。

from threading import Thread
import time as t
x=1
z=1
var=0
def firstFunction():
global var
while x == 1:
var += 1
t.sleep(1)
def secondFunction():

while z == 1:
see1=input("See var? : ")
if see1 == "y":
print(var)
elif seel == "n":
print("ok")
else:
print("not option")
add=Thread(target=firstFunction)
see=Thread(target=secondFunction)
add.start()
see.start()

最佳答案

当你像这样运行你的代码时,主线程将到达终点并在启动两个子线程后直接终止。

您必须等到线程完成。 .join() 将执行此操作,因此您只需将这些行添加到程序的最后

add.join()
see.join()

主线程会一直等到两个线程都完成。

请注意,不幸的线程和连接组合可能会导致死锁。

关于Python线程在1个循环后卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47655075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com