views:

124

answers:

2

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?

+1  A: 

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

Schildmeijer
+1  A: 

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".

Jeremy W. Sherman