我尝试每 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
showprogress 函数永远不会被执行
最佳答案
这应该有效。你的之所以没有,是因为你将函数 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()
关于python - 一个带有 'while' 的线程 python 得到另一个线程从未启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532837/