How to immediately re-raise an exception thrown in any of the worker threads?
<p>I'm using <code>ThreadPoolExecutor</code> and need to abort the whole computation in case any of the worker threads fails.</p>

<p><strong>Example 1.</strong> This prints <em>Success</em> regardless of the error, since <code>ThreadPoolExecutor</code> does not re-raise exceptions automatically.</p>

<pre><code>from concurrent.futures import ThreadPoolExecutor

def task():
    raise ValueError

with ThreadPoolExecutor() as executor:
    executor.submit(task)
print('Success')
</code></pre>

<p><strong>Example 2.</strong> This correctly crashes the main thread because <code>.result()</code> re-raises exceptions. But it waits for the first task to finish, so the main thread experiences the exception with a delay.</p>

<pre><code>import time
from concurrent.futures import ThreadPoolExecutor

def task(should_raise):
    time.sleep(1)
    if should_raise:
        raise ValueError

with ThreadPoolExecutor() as executor:
    executor.submit(task, False).result()
    executor.submit(task, True).result()
print('Success')
</code></pre>

<p>How can I notice a worker exception in the main thread (more or less) immediately after it occurred, to handle the failure and abort the remaining workers?</p>