Python线程未实现并发执行问题求助
Python线程同步执行问题排查与修复
问题代码与预期不符情况
你编写的Python线程代码如下:
from time import sleep import threading def sleep_and_print(duration, name): sleep(duration) print(name) t1 = threading.Thread(target=sleep_and_print(2, "three second sleep")) t2 = threading.Thread(target=sleep_and_print(1, "one second sleep")) t1.start() t2.start() t1.join() t2.join()
预期线程异步启动,先打印one second sleep,再打印three second sleep,但实际代码是同步执行,尝试ThreadPoolExecutor也未达到预期效果。
问题根源
核心错误是创建Thread对象时,直接调用了目标函数,而非传递函数的引用:
target=sleep_and_print(2, "three second sleep")会立即执行sleep_and_print函数,等函数执行完毕后,才将其返回值(此处为None)传给target参数。这就导致代码先同步执行完t1对应的函数,再执行t2的函数,完全没有线程异步的效果。
修复方案
1. 使用threading.Thread的正确写法
传递函数本身作为target,通过args参数传入函数所需的参数(参数需以元组形式传递):
from time import sleep import threading def sleep_and_print(duration, name): sleep(duration) print(name) # 正确传递函数引用和参数 t1 = threading.Thread(target=sleep_and_print, args=(2, "three second sleep")) t2 = threading.Thread(target=sleep_and_print, args=(1, "one second sleep")) t1.start() t2.start() t1.join() t2.join()
2. 使用ThreadPoolExecutor的正确写法
同样要避免直接调用函数,通过submit方法传递函数和参数:
from time import sleep from concurrent.futures import ThreadPoolExecutor def sleep_and_print(duration, name): sleep(duration) print(name) with ThreadPoolExecutor(max_workers=2) as executor: executor.submit(sleep_and_print, 2, "three second sleep") executor.submit(sleep_and_print, 1, "one second sleep")
修改后,两个线程会异步执行,最终会先打印one second sleep,再打印three second sleep,符合预期。
内容的提问来源于stack exchange,提问作者GC30
相关产品推荐
相关产品推荐

