我在下面有这个小的线程测试代码。线程名称有时是执行程序的名称,有时是主线程的名称。根据 3.7 Python 文档add_done_callback(注)...添加的可调用对象按添加顺序调用,并且始终在属于添加它们的进程的线程中调用。
为什么我随机获得不同的线程名称?
from concurrent.futures import ThreadPoolExecutor
import threading
def task(n):
print(f'task - Thread: {threading.current_thread().name}')
print("Processing {}".format(n))
ttask()
def ttask():
print(f'ttask - Thread: {threading.current_thread().name}')
print("Processing ")
def taskDone(fn):
print(f'taskDone - Thread: {threading.current_thread().name}')
if fn.cancelled():
print("Our {} Future has been cancelled".format(fn.arg))
elif fn.done():
print("Our Task has completed")
def secondTaskDone(fn):
print(f'secondaTaskDone - Thread: {threading.current_thread().name}')
print("I didn't think this would work")
def main():
print("Starting ThreadPoolExecutor")
print(f'Thread: {threading.current_thread().name}')
with ThreadPoolExecutor(max_workers=3) as executor:
print(f'Thread: {threading.current_thread().name}')
future = executor.submit(task, (2))
future.add_done_callback(taskDone)
future.add_done_callback(secondTaskDone)
print("All tasks complete")
if __name__ == '__main__':
main()
输出是随机的:
输出 1:
Starting ThreadPoolExecutor
Thread: MainThread
Thread: MainThread
task - Thread: ThreadPoolExecutor-0_0
Processing 2
ttask - Thread: ThreadPoolExecutor-0_0
Processing
taskDone - Thread: ThreadPoolExecutor-0_0
Our Task has completed
secondaTaskDone - Thread: ThreadPoolExecutor-0_0
I didn't think this would work
All tasks complete
产出2:
Starting ThreadPoolExecutor
Thread: MainThread
Thread: MainThread
task - Thread: ThreadPoolExecutor-0_0
Processing 2
ttask - Thread: ThreadPoolExecutor-0_0
Processing
taskDone - Thread: MainThread
Our Task has completed
secondaTaskDone - Thread: MainThread
I didn't think this would work
All tasks complete
本主题中回答了问题。谢谢你的@dano。Python ThreadPoolExecutor - 回调是否保证与提交的函数在同一线程中运行?
为 ttask() 添加了 0.2s 延迟,回调始终在 "ThreadPoolExecutor-0_0" 中运行。
此问题可以与上述主题重复关闭。