What is the asymchronism?

Asked

Viewed 8,548 times

15

In a question about use or not use Node Js, I ended up having to give an explanation about what is the asynchronymism.

And it seems that the community would benefit in a general way from a formal explanation of What is asymchronism after all?.

Although I intend to re-take advantage of the content I posted everyone is invited to reply.

References:

I refer to the question How asynchronous programming works in Javascript. However the intention is to explain abstractly and without connection to any language what is and how the asynchronous programming works.

Reference to What is the real advantage of using a Callback and what is thread/multithread?. Both the question and the answer touch on this topic, but all part of a means to an end. Before realizing what callbacks are and how callbacks are used in asynchronous programming it is necessary to understand what it is.

  • See if the drawing in this answer helps http://answall.com/a/45721/3635 :)

  • 1

    @Guilhermenascimento I added to the references, thank you for your contribution, and congratulations on your good answer to this question.

2 answers

25

Definitions

Synchronous or asynchronous relates to the execution flow of a program. When an operation executes completely before passing control to the next, the execution is synchronous. This is the standard method of code execution - in the languages I know, and I imagine also in most of the languages I don’t know.

When one or more operations are time consuming, it may be interesting to run them asynchronous, so that the rest of the code can be executed without waiting for them to finish. In this case, the code following the command that triggers the asynchronous operation cannot count on the result of this operation, of course. Everything that depends on the result of the operation needs to be done only when it has been completed, and usually this occurs in a callback, that is, a code block (usually a function or method) reported to the command that starts the asynchronous operation.

Languages can implement asynchronism in different ways. Usually this is done with Threads and event loops, as in Javascript.

Examples

In Javascript, in the browser, the classic case of asynchronous operation is AJAX - English acronym for Javascript and XML asynchronous. We call AJAX the requests made to a server from JS on a web page. For example, with jQuery to abbreviate:

$.get('http://example.com', funcaoQueExecutaQuandoRespostaChegar);

// o código seguinte executa antes da resposta da requisição acima
fazAlgumaCoisa();

// e a declaração do callback
function funcaoQueExecutaQuandoRespostaChegar(resposta) {
    // a resposta não pode ser usada fora daqui,
    // a menos que você a passe, a partir daqui,
    // para uma outra função
}

As the request is potentially time consuming (and certainly longer than any local operation), if it is done synchronously the page will be frozen until the answer arrives. Therefore it is recommended to use AJAX and callbacks in such cases.

Another typical example occurs in the Desktop application user interface. If the program wants to show a progress bar indicating the progress of a time-consuming operation, it must necessarily use asynchrony. Otherwise the interface can only update the progress bar once at the end of the operation - which would make no sense for a progress bar!

  • This is an excellent start, thank you for starting by defining what asynchronous is and still touching the difference between synchronous and asynchronous execution. But I am looking for an answer that can explain to practically a child and that is quite complete.

  • 2

    Okay. I’m unfortunately running out of time to write very detailed answers. Who knows in the future :) I wanted to answer because that my answer about js is too technical and for a very specific audience, and I saw an opportunity to leave the definitions here, succinctly. I also hope that better and more complete answers will appear.

  • 1

    I added a little bit. I leave it to others to talk about issues and how to "tame" asynchronous code.

8


What is the asynchrony?

Synchronous or asynchronous refers to the execution flow of a program. When an operation runs completely before passing control to the next, the execution is synchronous. @bfavaretto

Follows an explanatory picture of the synchronous and asynchronous execution flow, withdrawal of my reply to When to use Node.js and when not to use?

inserir a descrição da imagem aqui One can make the analogy of an asynchronous operation to the scheduling of an operation. The thread schedules the operation and can continue the execution normally. When the asynchronous operation is completed the thread has opportunity to process its result. This opportunity is usually created using callbacks (Pointers to functions).

Let’s give an example: Make an asynchronous request to the SE API, when this request is complete runs function A

var now = performance.now();
var request = new XMLHttpRequest();

function A() {
  if (request.readyState == 4 && request.status == 200) {
    document.getElementById("result").textContent = "API SE " + ~~(performance.now() - now) + "ms";
  }
}
request.onreadystatechange = A; //quando este pedido estiver completo executa a função A
request.open('GET', 'https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow', true);
request.send(); //faz um pedido assincrono à API do SE
<p id="result"></p>

When and why it is useful to program asynchronously?

  • When an operation takes time

If an operation is time consuming the thread that is running it would have to wait until it completes.

  • Not to block the user-interface (same reason above, viewed in a different way)

Usually user-interfaces process events (button clicks, mouse movement, keys, ...). These same events should not take long before the user-interface can continue to process them.

  • When an operation is an I/O operation

What’s not the asynchrony?

  • Asynchronous operations do not guarantee any parallelism except if they are I/O operations.
  • Asynchronous operations do not involve other threads for code execution

Why is the asynchronous I/O is "special"?

This is the only type of asymchronism that allows parallelism, this parallelism always occurs at the level of distinct hardware CPU (disks, network cards, ...).

As I showed in Image 1 if the I/O requests were asynchronously the total time would be shorter. Total time can be calculated:

Tempo total = Max(Processamento I/O A, Processamento I/O B) + Processa A + Processa B
  • I did not accept @bfavarento’s reply because he did not speak of the asynchronous I/O and due to the organization of his reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.