Search code examples
c++iocp

How to make asynchronous read of a file with IOCP?


I have faced an implementation problem. I am puzzled on how to implement IOCP. I have read a lot on the Internet about it, but still missing one step. So far what I have learnt is as follows: In order to use IOCP:

  1. on an init function:
CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); // to have a max thread number available
handler = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED , 0);
CreateIoCompletionPort(handler, NULL, 0, 0); // to associate my handler with an IOCP
  1. on a read funcion I can do sth like that:
ReadFile(..., &Overlapped); // this will return error == ERROR_IO_PENDING which is what I want - asynch read
  1. now I have difficulties to understand next steps. Should I spawn a thread after ReadFile and wait inside that thread until GetQueuedCompletionStatus is true?

Solution

  • So the answer for my question is here:

    https://stackoverflow.com/a/680416/2788176

    In very simplistic (and a little over-simplified) terms, you tell the IOCP about the IO jobs you want done. It will perform them asynchronously and maintain a queue of the results of each of those jobs. Your call to tell the IOCP about the job returns immediately (it does not block while the IO happens). You are returned an object that is conceptually like the .NET IAsyncResult ... it lets you block if you choose to, or you can provide a callback, or you can periodically poll to see if the job is complete.

    IOCP implementation can be found in windows SDK.