Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a blocking function?

What is a blocking function or a blocking call?

This is a term I see again and again when referring to Node.js or realtime processing languages.

like image 336
cjm2671 Avatar asked Sep 13 '11 19:09

cjm2671


2 Answers

A function that stops script execution until it ends.

For example, if I had a function in my language that was used to write to a file, like so:

fwrite(file, "Contents");
print("Wrote to file!");

The print statement would only be executed once the file has been written to the disk. The whole program is halted on this instruction. This isn't noticeable for small enough writes, but imagine I had a huge blob to write to the file, one that took many seconds:

fwrite(file, blob);
print("Wrote to file!");

The print statement would only be executed after a few seconds of writting, and the whole program would be stopped for that time. In Node.js, this stuff is done asynchronously, using events and callbacks. Our example would become:

fwrite(file, blob, function() {
    print("Wrote to file!");
});
print("Do other stuff");

Where the third parameter is a function to be called once the file has been written. The print statement located after the write function would be called immediately after, whether or not the file has been written yet. So if we were to write a huge enough blob, the output might look like this:

Do other stuff
Wrote to file!

This makes applictions very fast because you're not waiting on a client message, a file write or other. You can keep on processing the data in a parallel manner. This is considered by many one of the strengths of Node.js.

like image 166
Alex Turpin Avatar answered Oct 07 '22 02:10

Alex Turpin


var block = function _block() {
  while(true) {
    readInputs();
    compute();
    drawToScreen();
  }
}

A blocking function basically computes forever. That's what it means by blocking.

Other blocking functions would wait for IO to occur

a non-blocking IO system means a function starts an IO action, then goes idle then handles the result of the IO action when it happens.

It's basically the difference between a thread idling and sleeping.

like image 45
Raynos Avatar answered Oct 07 '22 02:10

Raynos