I was looking on how the twisted and node.js frameworks work and I am trying to understand exactly how the operating system supports I/O operations using callbacks.
I understand it's good because we need less threads because we don't need to have blocked threads waiting for I/O operations. But something has to call the callback once the I/O is finished.
How is this implemented by the operating system?
When you perform an action on a graphical component you generate an event. In event-driven programming the program responds to events. The program responds to events that the user generates in interacting with GUI components. The order of events is controlled by the user.
Event-Driven Programming js uses events heavily and it is also one of the reasons why Node. js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur.
One approach is to have the OS attach information about anyone waiting for a callback to the relevant data structure, such as the in-kernel equivalent of the file descriptor you're waiting for read notification about. When something happens to that file descriptor, the OS scans the waiters to see if any should be notified. If they should, then it does so. You can read about one implementation of this in Lemon's paper introducing FreeBSD's kqueue
mechanism. See in particular section 6, "Implementation", subsections 3 and 4, "Activity on Event Source" and "Delivery".
This is solved in OS by using "I/O event notification facilities/interfaces", e.g epoll, poll, kqueue or select.
Take a look at deft, and especially its' io/event loop for a concrete example how the "notification systems" mentioned above are used. (java.nio.channels.Selector is the java nio way to provide an abstraction for this.)
disclaimer: im a deft committer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With