我有下面这个小线程测试代码。线程名称有时是执行者的名称有时是主线程的名称。根据3.7 Python doc 添加\u完成\u回调(fn) ... 添加的可调用项按添加顺序调用,并且总是在属于添加它们的进程的线程中调用。
为什么随机得到不同的线程名称?你知道吗
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 - is the callback guaranteed to run in the same thread as submitted func?
为ttask()添加了0.2s延迟,回调总是在“ThreadPoolExecutor-0\u 0”中运行。你知道吗
此问题可与上述主题重复结束。你知道吗
相关问题 更多 >
编程相关推荐