我似乎无法让多线程工作。我简化了我的问题,但我仍然无法正确打印线程(所以我猜它们执行不正确(。
import time, threading
s_print_lock = threading.Lock()
def s_print(*a, **b):
with s_print_lock:
print(*a, **b)
# Thread safe print function
def a():
while True:
s_print(''a' is running')
time.sleep(5)
# Thread 1
def b():
while True:
s_print(''b' is running')
time.sleep(5)
# Thread 2
if __name__ == "__main__":
t1 = threading.Thread(target=a())
t2 = threading.Thread(target=b())
t1.start()
t2.start()
输出为:
'a' is running
'a' is running
'a' is running
'a' is running
...
目标必须是可调用的。您正在执行a()
,因此它进入while True
循环并且永远不会结束,因此永远不会启动线程。试试这个:
if __name__ == "__main__":
t1 = threading.Thread(target=a)
t2 = threading.Thread(target=b)
t1.start()
t2.start()