Skip to content

Instantly share code, notes, and snippets.

@DaveRandom
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaveRandom/91d3dce819aa3bef53ee to your computer and use it in GitHub Desktop.
Save DaveRandom/91d3dce819aa3bef53ee to your computer and use it in GitHub Desktop.

Asynchronous and parallel programming are both forms of concurrency ...

I'll try to explain ... (this may not work, I'm not good at explain)

The following diagram shows the (familiar) synchronous model of execution, lets call it program X, has three tasks to complete:

 ---      ||
| 0 |     ||
| 0 |     ||
| 0 |     ||
| 0 |     ||
| 0 |    \  /
| 0 |     ||
|---|     ||
| 1 |     ||
| 1 |     ||
| 1 |    Time
| 1 |     ||
| 1 |     ||
| 1 |     ||
|---|     ||
| 2 |    \  /
| 2 |     ||
| 2 |     ||
| 2 |     ||
| 2 |     ||
| 2 |    \  /
 ---      ||

Nice and simple, this is what most of us are used too.

The following diagram shows a parallel model of execution, in this model there are three threads of execution running separate tasks:

 -----------
| 0 | 1 | 2 |
| 0 | 1 | 2 |
| 0 | 1 | 2 |
| 0 | 1 | 2 |
| 0 | 1 | 2 |
| 0 | 1 | 2 |
 --- -------

We can actually see that these tasks run truly concurrently, concurrently with respect to time, reducing the overall time it takes to execute the three tasks.

The following diagram shows the asynchronous model:

 ---      ||
| 2 |     ||
| 1 |     ||
| 0 |     ||
| 1 |     ||
| 0 |    \  /
| 1 |     ||
|---|     ||
| 1 |     ||
| 2 |     ||
| 1 |    Time
| 0 |     ||
| 1 |     ||
| 2 |     ||
|---|     ||
| 0 |    \  /
| 0 |     ||
| 2 |     ||
| 2 |     ||
| 2 |     ||
| 0 |    \  /
 ---      ||

We can see that the tasks are interleaved by the programmer, forcing the tasks to execute concurrently with respect to each other, but it seems to take as long as the synchronous model to execute.

Where asynchronous concurrency is useful is usually in the case of I/O bound code, where a considerable amount of time for each task is actually spent waiting.

 ---      ||
| 0 |     ||
| - |     ||
| - |     ||
| - |     ||
| 0 |    \  /
| 0 |     ||
|---|     ||
| 1 |     ||
| - |     ||
| - |    Time
| - |     ||
| 1 |     ||
| 1 |     ||
|---|     ||
| 2 |    \  /
| - |     ||
| - |     ||
| - |     ||
| 2 |     ||
| 2 |    \  /
 ---      ||

Instead of waiting for the remote party to respond, your interleaved instructions can continue executing:

 ---      ||
| 2 |     ||
| 0 |     ||
| 1 |     ||
| 0 |    \  /
|---|     ||
| 2 |     ||
| 1 |    Time
| 0 |     ||
| 2 |     ||
|---|     ||
| 1 |     ||
| 1 |     ||
| 2 |     ||
| 0 |    \  /
 ---      ||

So asynchronous concurrency can also reduce the time it takes to execute the same I/O bound instructions by executing another tasks instructions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment