3I often use the following pattern in Python:
6for task in get_tasks_to_do():
10Tasks run one after the other: task 1 runs to completion, then task 2 runs to completion, then task 3 runs to completion, and so on until everything is done.
12This is fine for certain classes of task, but if
`perform()` is heavily I/O bound, it's unnecessarily slow.
13If I could run multiple instances of
`perform()` concurrently, the overall process would complete much faster.
14Task 1 could start, make a network request, then task 2 could start while task 1 is waiting.
16I wrote [
my recipe for concurrent processing][
blog] in a blog post in 2019, which explains how it works – but the code was a little cumbersome to use.
17This repo is a tidied up (and tested!) version of that code.
19It allows me to write code like:
22from concurrently import concurrently
24for (input, output) in concurrently(handler=perform, inputs=get_tasks_to_do()):
28It yields both the input and the output, because results may not come in the original order of inputs.
30I would recommend using this code instead of the code in the original blog post.
32[
blog]:
https://alexwlchan.net/2019/adventures-with-concurrent-futures/
38Copy and paste the file
`concurrently.py` into your project.
40You can see examples in the [
`examples` directory](./examples).