import time
import threading
def func(a):
index=1
while a:
print('loop' + str(index))
index += 1
time.sleep(1)
a = True
threading.Thread(target=func, args=(a,)).start()
time.sleep(3)
a = False
上面代码你会发现循环停止不下来, 因为a是值传递。
解决方法:
import time
import threading
def func(a):
index = 1
while a[0]:
print('===' + str(id(a)))
print('loop' + str(index))
index += 1
time.sleep(1)
a = [True]
print('before=' + str(id(a)))
threading.Thread(target=func, args=(a,)).start()
time.sleep(3)
a[0] = False
print('after=' + str(id(a)))