15

Which part of syntax provides the information that this function should run in other thread and be non-blocking?

Let's consider simple asynchronous I/O in node.js

 var fs = require('fs');
 var path = process.argv[2];

  fs.readFile(path, 'utf8', function(err,data) {
   var lines = data.split('\n');
   console.log(lines.length-1);
  });

What exactly makes the trick that it happens in background? Could anyone explain it precisely or paste a link to some good resource? Everywhere I looked there is plenty of info about what callback is, but nobody explains why it actually works like that.

This is not the specific question about node.js, it's about general concept of callback in each programming language.

EDIT:

Probably the example I provided is not best here. So let's do not consider this node.js code snippet. I'm asking generally - what makes the trick that program keeps executing when encounter callback function. What is in syntax that makes callback concept a non-blocking one?

Thanks in advance!

13
  • You already have answers, but you can read that too javascript callback : functions are objects Commented Apr 26, 2015 at 21:15
  • There's no way to generalize this. Callbacks run when they're called, and that depends entirely on what you're passing the callback to, regardless of the language. Commented Apr 26, 2015 at 21:15
  • nothing in the code you posted has anything to do with async processing. In fact, JavaScript is not a multi-threaded language, so you can never actually "trigger something to happen in the background". you can, however, simulate async behavior by using some third party library like Q that easily creates promise chains. Some core node functions may operate on a different thread, but you do not have access to them and cannot control their behavior. Commented Apr 26, 2015 at 21:19
  • 1
    Nothing in JavaScript's syntax defines sync v. async. Commented Apr 26, 2015 at 21:27
  • Maybe another way to ask this question would be... If I wanted to write a simple JavaScript function which accepted another function as an argument and invoked that function without blocking the caller, how would I write it? Commented Apr 26, 2015 at 21:41

3 Answers 3

32

There is nothing in the syntax that tells you your callback is executed asynchronously. Callbacks can be asynchronous, such as:

setTimeout(function(){
    console.log("this is async");
}, 100);

or it can be synchronous, such as:

an_array.forEach(function(x){
    console.log("this is sync");
});

So, how can you know if a function will invoke the callback synchronously or asynchronously? The only reliable way is to read the documentation.

You can also write a test to find out if documentation is not available:

var t = "this is async";
some_function(function(){
    t = "this is sync";
});

console.log(t);

How asynchronous code work

Javascript, per se, doesn't have any feature to make functions asynchronous. If you want to write an asynchronous function you have two options:

  1. Use another asynchronous function such as setTimeout or web workers to execute your logic.

  2. Write it in C.

As for how the C coded functions (such as setTimeout) implement asynchronous execution? It all has to do with the event loop (or mostly).

The Event Loop

Inside the web browser there is this piece of code that is used for networking. Originally, the networking code could only download one thing: the HTML page itself. When Mosaic invented the <img> tag the networking code evolved to download multiple resources. Then Netscape implemented progressive rendering of images, they had to make the networking code asynchronous so that they can draw the page before all images are loaded and update each image progressively and individually. This is the origin of the event loop.

In the heart of the browser there is an event loop that evolved from asynchronous networking code. So it's not surprising that it uses an I/O primitive as its core: select() (or something similar such as poll, epoll etc. depending on OS).

The select() function in C allows you to wait for multiple I/O operations in a single thread without needing to spawn additional threads. select() looks something like:

select (max, readlist, writelist, errlist, timeout)

To have it wait for an I/O (from a socket or disk) you'd add the file descriptor to the readlist and it will return when there is data available on any of your I/O channels. Once it returns you can continue processing the data.

The javascript interpreter saves your callback and then calls the select() function. When select() returns the interpreter figures out which callback is associated with which I/O channel and then calls it.

Conveniently, select() also allows you to specify a timeout value. By carefully managing the timeout passed to select() you can cause callbacks to be called at some time in the future. This is how setTimeout and setInterval are implemented. The interpreter keeps a list of all timeouts and calculates what it needs to pass as timeout to select(). Then when select() returns in addition to finding out if there are any callbacks that needs to be called due to an I/O operation the interpreter also checks for any expired timeouts that needs to be called.

So select() alone covers almost all the functionality necessary to implement asynchronous functions. But modern browsers also have web workers. In the case of web workers the browser spawns threads to execute javascript code asynchronously. To communicate back to the main thread the workers must still interact with the event loop (the select() function).

Node.js also spawns threads when dealing with file/disk I/O. When the I/O operation completes it communicates back with the main event loop to cause the appropriate callbacks to execute.


Hopefully this answers your question. I've always wanted to write this answer but was to busy to do so previously. If you want to know more about non-blocking I/O programming in C I suggest you take a read this: http://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html

For more information see also:

Sign up to request clarification or add additional context in comments.

17 Comments

This is a fantastic answer.
@szeb libuv internally will choose the appropriate async I/O library at compile time so it is still select() or something similar such as poll, epoll etc. depending on OS so there is no update. Node was using solely libevent when I wrote this answer but that does not change this answer at all since libevent and now libuv still do 100% what this answer is explaining. This is a forever correct answer
@szeb If you want a much deeper explaination of how OSes provide services such as select, poll, epoll, Overlapped I/O (Windows) etc. that libuv uses check out my much lower level answer to this related question: stackoverflow.com/questions/61262054/…
Progressive rendering means -> i.sstatic.net/BtI3d.gif
@SmartHumanism Interrupts. It's a hardware feature of your CPU. An interrupt is like a function call but instead of being triggered by software it is triggered by hardware (a signal wire changes voltage). Wikipedia has a fairly good article on interrupts: en.wikipedia.org/wiki/Interrupt. In my opinion the best way to understand interrupts is to try designing your own CPU. The basic concept of interrupts is very simple: it is simply a hardcoded function call. The CPU is simply DESIGNED to load a hardcoded memory address when a given interrupt happens..
|
0

First of all, if something is not Async, it means it's blocking. So the javascript runner stops on that line until that function is over (that's what a readFileSync would do).

As we all know, fs is a IO library, so that kind of things take time (tell the hardware to read some files is not something done right away), so it makes a lot of sense that anything that does not require only the CPU, it's async, because it takes time, and does not need to freeze the rest of the code for waiting another piece of hardware (while the CPU is idle).

I hope this solves your doubts.

4 Comments

thank you but I'm asking about something else. Which part of syntax, generally - maybe node.js is the bad example here, tells "do it in background"
@DCDC There's nothing in JavaScript syntax that defines this.
Oh, I thought you asked why. The callback argument is because that's how the API is, and makes sense because what I've just said early. If you want to understand how is that async, you could read about multi-threading, or how the javascript engine supports async code by implementing the event loop developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop but if you'd like to get really into the question, it'll be C++ code, not JS
could you explain using C++ then? Thanks!
0

A callback is not necessarily asynchronous. Execution depends entirely on how fs.readFile decides to treat the function parameter.

In JavaScript, you can execute a function asynchronously using for example setTimeout.

Discussion and resources:

How does node.js implement non-blocking I/O?

Concurrency model and Event Loop

Wikipedia:

There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).

3 Comments

ok, so maybe this is a bad example, but generally passing block of code runs asynchronously, doesn't it?
@DCDC There's no way to generalize that. Callbacks run when they're called, and that depends entirely on what you're passing the callback to.
Passing a function does nothing. Something must execute that function and that can be done any way the developer wants. Example: jsfiddle.net/pfudnyh6/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.