What is asynchrony?

11

In a question about using or not using Node Js , I ended up giving an explanation of what is asynchrony .

And it seems that the community would generally benefit from a formal explanation of What is asynchronism after all?

Despite having intentions to re-seize the content I posted all are invited to respond.

References:

I already refer to the question How asynchronous programming works in JavaScript . However the intention is to explain in an abstract way and without connection to any language what is and how 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 they are used in asynchronous programming it is necessary to realize what it is.

    
asked by anonymous 19.04.2016 / 19:42

2 answers

5

What is asynchrony?

  

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

Following is an explanatory image of the synchronous and asynchronous execution flow, removed from my response to When to use Node.js and when not to use?

Youcanmaketheanalogyofanasynchronousoperationwhenschedulinganoperation.Thethreadschedulestheoperationandcancontinuerunningnormally.Whentheasynchronousoperationiscompletedthethreadhastheopportunitytoprocessitsresult.Thisopportunityisusuallycreatedusingcallbacks.

Let'sgiveanexample:MakeanasynchronousrequesttotheSEAPI,whenthisrequestiscompleteitexecutesfunctionA

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 is it helpful to program asynchronously?

  • When an operation is delayed

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

  • To not block the user-interface (same reason above, seen differently)

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

  • When an operation is an I / O operation

What is not asynchronous?

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

Why is asynchronous I / O "special"?

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

As I showed in Figure 1 if the I / O requests went asynchronously, the total time would be less. The total time can be calculated:

Tempo total = Max(Processamento I/O A, Processamento I/O B) + Processa A + Processa B
    
20.04.2016 / 23:00
18

Settings

Synchronous or asynchronous refers to the execution flow of a program. When an operation executes completely before passing the control to the next, the execution is synchronous . This is the standard method of code execution - in languages I know, and I imagine that in most languages I do not know.

When one or more operations are time-consuming, it may be worthwhile to execute them asynchronously, so that the rest of the code can be executed without waiting for them to stop. In this case, the code following the command that triggers the asynchronous operation can not 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 block of code (usually a function or method) the asynchronous operation.

Languages can implement asynchronism in different ways. This is usually done with Threads and Event Loops, like as in JavaScript .

Examples

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

$.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 more time-consuming than any local operation), if the request is synchronous the page will be frozen until the response arrives. Therefore it is recommended to use AJAX and callbacks in these 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 asynchronism. Otherwise the interface can only update the progress bar once, at the end of the operation - which would not make any sense to a progress bar!

    
19.04.2016 / 20:34