I have this small threading testing code below. The thread name is sometimes the name of the executor sometimes the MainThread. According to 3.7 Python doc add_done_callback(fn) ... Added callables are called in the order that they were added and are always called in a thread belonging to the process that added them.
Why do I get different thread name randomly?
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()
The outputs are randomly:
output 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
output 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