Coming from a .Net background I am trying to understand python multithreading using concurrent.futures.ThreadPoolExecutor
and submit
. I was trying to add a timeout to some code for a test but have realised I don't exactly understand some elements of what I'm trying to do. I have put some simplified code below. I would expect the method to return after around 5 seconds, when the call to concurrent.futures.wait(futures, return_when=FIRST_COMPLETED)
completes. In fact it takes the full 10 seconds. I suspect it has to do with my understanding of the with
statement as changing the code to thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=2)
results in the behvaiour I would expect. Adding a call to the shutdown
method doesn't do anything as all the futures are already running. Is there a way to exit out of the with
statement immediately following the call to wait
? I have tried using break
and return
but they have no effect. I am using python 3.10.8
from concurrent.futures import FIRST_COMPLETED
import threading
import concurrent
import time
def test_multiple_threads():
set_timeout_on_method()
print("Current Time =", datetime.now()) # Prints time N + 10
def set_timeout_on_method():
futures = []
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_pool:
print("Current Time =", datetime.now()) # Prints time N
futures.append(thread_pool.submit(time.sleep, 5))
futures.append(thread_pool.submit(time.sleep, 10))
concurrent.futures.wait(futures, return_when=FIRST_COMPLETED)
print("Current Time =", datetime.now()) # Prints time N + 5
print("Current Time =", datetime.now()) # Prints time N + 10