Ridwan Yusuf
2 min readNov 20, 2022

--

Asynchronous programming a better concurrency Part 4

A quick recap from Part 1:
Concurrency refers to dealing with multiple tasks by switching context between them.

Synchronous programming is when a line of code will start its execution only when the previous line of code has completed its execution even if the previous code takes long.

Sample code:
Line 1: getUserInfo()
Line 2: procesUserInfo()
Line 3: sendMailToUser()

In Synchronous Programming, Line 2(i.e. processUserInfo()) will only start its execution execution when Line 1(processUserInfo()) is completed. Line 3 (sendMailToUser()) will only start after Line 2. This is a blocking architecture because when one operation is ongoing, all other operations are blocked.

Asynchronous Programming(non-blocking) on the other hand behaves differently. processUserInfo() on line 2 can start without waiting for getUserInfo() on line 1 to finish. sendMailToUser() can start without waiting for processUserInfo() or getUserInfo() to finish.

You may ask that why are we not using multithreading(a kind of concurrency) instead?

Aside some drawbacks mentioned previous in previous posts, context switching in multithreaded code is controlled cleverly by the OS.
The switch between threads can happen anytime and that can be when a statement is being executed.

Asynchronous Programming provides a kind of resume/pause. You will start getUserInfo() on line 1, move on to doing other thing like processUserInfo() on line 2. It provides a way to let you know that line 1 is done with that long process that requires waiting (but you are not waiting in Asynchronous) so that you resumed back to line 1 when you are notified that it's done for you to continue its execution.

Note: An async program runs in single process and a single thread.

It should be noted that asynchronous programming only fit where the tasks are independent(i.e. task A does not depend on some output from Task B ).

So when should you use which:
1. CPU Bound operations: mathematical computations, image processing, etc. use Multiprocessing

2.I/O Bound, Fast I/O, Limited Number of Connections : network get request, database queries, etc. Use Multithreading

3.I/O Bound, Slow I/O, Many connections : lots of frequent File r/w,

Further reading on Real Python blogs.

Enjoyed this article?

Feel free to explore my video collection on YouTube for more educational content. Don’t forget to subscribe to the channel to stay updated with future releases.

--

--

Ridwan Yusuf

RidwanRay.com -I provide engineers with actionable tips and guides for immediate use