一个线程 python 与 'while' 有另一个线程永远不会启动



我正在尝试添加一个数字一次 1 秒,每 3 秒监控一次结果 2 次。我尝试在 python 中使用线程,但由于一个线程正在运行,另一个线程永远不会启动。

import threading, time
a = 0
def a1():
print('adding')
global a
while a < 1000:
a+=1
print('a from a1', a)
time.sleep(1)

def showprogress():
global a
print(a)
time.sleep(3)
print(a)
time.sleep(3)
print(a)
t1 = threading.Thread(target=a1())
t2 = threading.Thread(target=showprogress())
t1.start()
t2.start()

下面是输出

adding
a from a1 1
a from a1 2
a from a1 3
a from a1 4
a from a1 5
a from a1 6
a from a1 7
a from a1 8

显示进度函数永远不会被执行

这应该有效。你的不这样做的原因是因为你正在传递函数,a1()到目标中。target接受一个可调用的对象,因此通过传入内部的整个函数,您实际要做的是传入返回值,在这种情况下None。 然后,showprogress()将在a()之后执行,这也将None传递到参数中。

如果你想将参数传递到你的函数中,你可以做的是

t1 = threading.Thread(target=a1 ,args=(4,0.25))(也就是说,如果您的函数接受参数。

import threading, time
a = 0
def a1():
print('adding')
global a
while a < 1000:
a+=1
print('a from a1', a)
time.sleep(1)

def showprogress():
global a
print(a)
time.sleep(3)
print(a)
time.sleep(3)
print(a)
t1 = threading.Thread(target=a1)
t2 = threading.Thread(target=showprogress)
t1.start()
t2.start()
t1.join()
t2.join()

最新更新