An analogy for `async`

I've realized a (relatively) common activity which has many parallels (ha) to async and threads: Cooking!


Cooking

If you're making a dish, you're not going to first make the sauce, and then the rice, and then the broccoli, and then the carrots, etc. It's just not feasible to do everything sequentially.
There's 2 main ways to solve this:

  1. Bring in a friend to help, but you gotta wait for them to come over, and there's only so many people you can have help you before you're all just getting in each other's way.
  2. Start one thing, then let that keep going while you do another. You could start the rice, then make the sauce, then the broccoli and carrots, and then put them all together

Of course, you can put these together, and have both you and your friend start one thing, and then go on to another.


Coding

If you're making a program, you're not going to first query the database, and then ping an API, and then read a file, etc. It's just not feasible to do everything sequentially.
There's 2 main ways to solve this:

  1. Spawn a thread, but you gotta wait for OS to create it, and there's only so many you can spawn before they all just start hogging each others CPU time.
  2. Start an async task, then go on to something else. You could send a request to the database, then ping the API, then read a file, and then get the response from them all.

Of course, you can put these together, and have many threads run async tasks.

1 Like

An example I see in Go all the time is ordering food at a restaurant. There are two main ways this could be done:

  1. The first person in the line gives their order, the order is sent to the kitchen, they wait for the food to be cooked, then take their food to a table and the next person in line steps up.
  2. The first person in the line gives their order, the order is sent to the kitchen, that person then walks off and finds a table to let the next person give their order. At some point later on, the person's food is ready and it gets brought out to them.

Following a similar line of thought, Rob Pike did a really good talk called Concurrency is not Parallelism.

It's framed in the context of Go, which uses a form of green threading (imagine everything is async, except the await is implicit), but a lot of the ideas are language-agnostic and he has an amusing example.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.