[Python-Dev] [PEP 3148] futures - execute computations asynchronously
Brian Quinlan
brian at sweetapp.com
Wed Mar 10 09:19:38 CET 2010
On 9 Mar 2010, at 08:39, Greg Ewing wrote:
> Terry Reedy wrote:
>> Looking more close, I gather that the prime results will be printed
>> 'in order' (waiting on each even if others are done) while the url
>> results will be printed 'as available'.
>
> Seems to me that if you care about the order of the results,
> you should be able to just wait for each result separately
> in the order you want them. Something like
>
> task1 = start_task(proc1)
> task2 = start_task(proc2)
> task3 = start_task(proc3)
> result1 = task1.wait_for_result()
> result2 = task2.wait_for_result()
> result3 = task3.wait_for_result()
You can write this as:
executor = ...
future1 = executor.submit(proc1)
future2 = executor.submit(proc2)
future3 = executor.submit(proc3)
result1 = task1.result()
result2 = task2.result()
result3 = task3.result()
> This would also be a natural way to write things even if
> you don't care about the order, but you need all the results
> before proceeding. You're going to be held up until the
> longest-running task completes anyway, so it doesn't matter
> if some of them finish earlier and have to sit around
> waiting for you to collect the result.
Often you don't want to continue if there is a failure.
In the example that you gave, if "proc3" raises an exception
immediately, you still wait for "proc1" and "proc2" to complete even
though you will end up discarding their results.
Cheers,
Brian
More information about the Python-Dev
mailing list