Asynchronous I/O with Threads
Overlapped and extended I/O achieve asynchronous I/O within a single thread, although the OS creates its own threads to support the functionality. These techniques are common, in one form or another, in many older OSs for supporting limited forms of asynchronous operation in single-threaded systems.Windows, however, supports threads, so the same effect is possible by performing synchronous I/O operations in multiple, separate threads. The multithreaded servers and Chapter 7's grepMT have already illustrated this. Threads also provide a uniform and, arguably, much simpler way to perform asynchronous I/O. An alternative to Program 14-1 and 14-2 is to give each thread its own handle to the file and each thread could synchronously process every fourth record.The atouMT.c program, not listed here but included on the book's Web site, illustrates how to use threads in this way. Not only does atouMT work on all Windows versions, but it is also simpler than the two asynchronous I/O programs because the bookkeeping is less complex. Each thread simply maintains its own buffers on its own stack and performs the read, convert, and write sequence synchronously in a loop. The performance is also competitive. Note: The atouMT.c program on the Web site contains some comments about several pitfalls that can occur when a single file is accessed concurrently from several threads. In particular, the distinct file handles should all be created with CreateFile rather than with DuplicateHandle.My personal preference is to use threads rather than asynchronous I/O for file processing. Threads are easier to program, and they provide the best performance in most cases.There are two exceptions to this generalization. The first exception, as shown earlier in this chapter, is a situation in which there is only a single outstanding operation and the file handle can be used for synchronization. The second, and more important, exception occurs with asynchronous I/O completion ports, as will be described at the end of this chapter.