如何使用 IOCP 异步读取文件?

How to make asynchronous read of a file with IOCP?

我遇到了实施问题。我对如何实施 IOCP 感到困惑。我已经在互联网上阅读了很多关于它的内容,但仍然缺少一步。 到目前为止,我所学到的如下: 为了使用 IOCP:

  1. 在初始化函数上:
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. 在读取功能上我可以这样做:
ReadFile(..., &Overlapped); // this will return error == ERROR_IO_PENDING which is what I want - asynch read
  1. 现在我很难理解接下来的步骤。我应该在 ReadFile 之后生成一个线程并在该线程内等待直到 GetQueuedCompletionStatus 为真吗?

所以我的问题的答案在这里:

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 实现可以在 windows SDK 中找到。