Search code examples
asynchronousnonblockingevent-driven

Can someone explain to me what is an event-driven, asynchronous, non-blocking I/O


I'm trying to understand these concepts

  • Event-driven
  • Asynchronous
  • non-blocking I/O

Solution

  • Imagine you read from a socket with this pseudo code

    void processIO(socket)
    {
       data = socket.read();
       doSomething(data);
    }
    

    The read method is used in a blocking mode. That means it does not continue until the data is read. The thread, this is running on is blocked and does not continue until the data is read. doSomething is only called once the data is read. If you did this on a main thread of an app, it would probably not be able to update its UI and would behave like frozen until the data is received.


    async void processIO(socket)
    {
       data = await socket.readAsync();
       doSomething(data);
    }
    
    

    This function is asynchronous and it itself calls an asynchronous readAsync() method. In this way, the thread this runs on is not blocked. It is interrupted at the await statement, and is available for other things in your app to run. Once the data is read, it resumes after the await statement and continues with doing something with the data. This is one way of doing non-blockig data processing however it is not event driven.


    void setupRead(socket)
    {
       socket.on_data(do_something);
    }
    
    void do_something(data) 
    {
      // process data
    }
    
    void main()
    {
       socket = new Socket(111)
       setupRead(socket)
       while (true) {
          processEvents()
       }
    }
    

    This last example demonstrates event driven IO. You register a callback on some resource to be called when some data arrives. In the mean time your code may do other things or do nothing. This is a non-blocking, asynchronous and event driven approach. The UI get's refreshed and the app may do whatever it needs to.

    Event Driven, means you setup event callbacks and wait for the events to happen. Asynchronous means, you do other stuff while waiting such as refreshing UI, processing user input or read from write from other resources.

    Non-blocking means the thread that started the listening, is not blocked until an event arrives, it does whatever else there is to do. Such as handle other events in the mean time.