I/O完成端口背后的理论是并发运行的线程的数量必须有一个上限。
看一段代码:
/ 异步方式调用.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> #include <iostream> using namespace std; PTP_WORK hWork = NULL; //定义工作项变量 HANDLE hPort; //定义I/O完成端口句柄 HANDLE hFile[4] = {0}; //enum Key{CK_READ1,CK_READ2,CK_READ3,CK_READ4} //线程池处理函数 VOID NTAPI WorkCallback(PTP_CALLBACK_INSTANCE Instance,PVOID Context) { DWORD dwNumBytes; ULONG_PTR CompletionKey; OVERLAPPED* pOverlapped = NULL; //不断等待,当有IO请求完成的时候,执行相应的操作 while(1) { BOOL bOk = GetQueuedCompletionStatus(hPort,&dwNumBytes,&CompletionKey,&pOverlapped,5000); DWORD dwError = GetLastError(); cout<<"完成等待"<<endl; if(bOk) { switch(CompletionKey) { case 0: cout<<"文件1"<<endl; //执行与文件1有关的其他操作,操作完成后,关闭句柄 CloseHandle(hFile[0]); break; case 1: cout<<"文件2"<<endl; CloseHandle(hFile[1]); break; case 2: cout<<"文件3"<<endl; CloseHandle(hFile[2]); break; case 3: cout<<"文件4"<<endl; CloseHandle(hFile[3]); break; default: cout<<"出现错误"<<endl; break; } } else { if(pOverlapped != NULL) { cout<<"pOverlapped != NULL"<<endl; } else if(dwError == WAIT_TIMEOUT) { cout<<" WAIT_TIMEOUT"<<endl; } else { cout<<"未知错误"<<endl; } } } cout<<"处理工作项"<<endl; } //创建新的I/O完成端口函数 HANDLE CreateNewCompletionPort(DWORD dwNumberOfConcurrentThreads) { return CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,dwNumberOfConcurrentThreads); } //设备与I/O完成端口关联函数 BOOL AssociateDeviceWithCompletionPort(HANDLE hCompletionPort,HANDLE hDevice,DWORD dwCompletionKey) { HANDLE h = CreateIoCompletionPort(hDevice,hCompletionPort,dwCompletionKey,0); return (h == hCompletionPort); } int _tmain(int argc, _TCHAR* argv[]) { LPCWSTR pszName[] = {_T("a1.txt"),_T("a2.txt"),_T("a3.txt"),_T("a4.txt")}; OVERLAPPED o = {0}; o.Offset = 0; BYTE bBuffer[100] = "abcde"; //打开文件句柄(共4个文件句柄) for(int i=0; i<4; ++i) { hFile[i] = CreateFile(pszName[i],GENERIC_WRITE,0,NULL,OPEN_ALWAYS,FILE_FLAG_OVERLAPPED,NULL); //FILE_FLAG_OVERLAPPED,异步IO标志 } //创建一个I/O完成端口 hPort = CreateNewCompletionPort(0); //将4个文件句柄与完成端口关联 for(int i=0; i<4;++i) { if(!AssociateDeviceWithCompletionPort(hPort,hFile[i],i)) { cout<<"完成端口关联失败"<<endl; } } if(FALSE == TrySubmitThreadpoolCallback(WorkCallback,NULL,NULL)) //创建一个线程池 { cout<<"线程池失败"<<endl; } //异步模式的4个IO请求,不影响主线程的继续运行 for(int i=0; i<4; ++i) { WriteFile(hFile[i],bBuffer,100,NULL,&o); DWORD dwError = GetLastError(); if(ERROR_IO_PENDING ==dwError) cout<<"进入了异步"<<endl; } cout<<"继续主线程"<<endl; for(int i = 0;i<100;++i) { cout<<i<<endl; } Sleep(5000); system("pause"); return 0; }