Search code examples
network-programmingasynchronousiononblockingevent-driven

How is event driven programming implemented?


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?


Solution

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