The concurrent paradigm

The concurrency models of languages and frameworks: threads and pools, promises, async/await and the event loop, actors; concurrency versus parallelism and the race condition.

  • 25 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Concurrency: what is it?

    Show the answer

    Structuring a program as tasks that each make progress in turn and overlap in time, even on a single core.

    It is a matter of organisation, not hardware: a server that serves a thousand clients on one thread is concurrent, because it moves to another client while the first one waits.

  • In what order does this JavaScript code print its letters?

    ```javascript
    console.log('A');
    setTimeout(() => console.log('B'), 0);
    Promise.resolve().then(() => console.log('C'));
    console.log('D');
    `

    • A D C B
    • A B C D
    • A D B C
    • A C D B
    Show the answer

    A D C B

    Synchronous code goes first (A, D). Then the loop drains the microtasks, which include promise callbacks (C), before it takes timers (B), even at 0 ms.

  • In a function declared …, the … keyword suspends the function until the promise settles, without blocking the event loop.

    Show the answer

    In a function declared async, the await keyword suspends the function until the promise settles, without blocking the event loop.

    During the suspension the loop runs other tasks; the function resumes at the next line when the result is ready. The code reads top to bottom but does not block.

  • Parallelism: what is it?

    Show the answer

    Running several computations at the very same instant, on several cores or machines.

    It needs extra hardware and is used to go faster on a heavy computation; concurrency is used to make good use of waiting time. You can have one without the other.

  • A Node.js server responds well, except when one request starts a five-second computation: during that time, every other request goes unanswered. What is the solution?

    • Move the computation into a worker thread to free the event loop
    • Add await in front of the computation so it stops blocking
    • Declare the route handler as async
    • Increase the clients' timeout
    Show the answer

    Move the computation into a worker thread to free the event loop

    The computation occupies the loop's only thread: nothing else gets through until it gives control back. await helps only for waiting (network, disk), not for pure computation, which must run elsewhere.