Sunday, February 7, 2016

Monitoring Files Asynchronously for Reading

There are a number of ways to monitor file descriptors asynchronously to determine when data is available to be read. Calling select() directly is getting to be old fashioned, but it still gets the job done. Because select() can block until data is available to be read, it should only be called from a background thread in a GUI application. In a daemon, it can be called from the primary thread as long as the daemon doesn't need to do anything else while it waits for data to become available.

The kqueue API is similar to select, and has the same limitations with respect to blocking threads.

Using libdispatch is a better option for GUI applications. The file descriptors can be monitored on a background thread and processed on the main thread.

Using NSFileHandle is an even simpler option for GUI applications. The only caveat is that the readability handler is called on a random thread. If you need to update your UI in response to something read from the file descriptor, you will need to move over to the main thread.

No comments:

Post a Comment