What is a blocking function?

前端 未结 3 1616
囚心锁ツ
囚心锁ツ 2021-02-20 03:59

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.

相关标签:
3条回答
  • 2021-02-20 04:07

    A blocking call is one that doesn't allow processing to continue until it returns to the calling thread - this is also referred to as a synchronous call. Asynchronous on the other hand means that threads (and code) can execute at the same time (concurrently).

    0 讨论(0)
  • 2021-02-20 04:11

    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.

    0 讨论(0)
  • 2021-02-20 04:24
    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.

    0 讨论(0)
提交回复
热议问题