● 异步I/0
○ 使用设备内核对象
○ 使用事件内核对象 提醒同步以及交互
○ 可提醒I/O 不可跨线程的
○ I/O完成端口
⊙ 使用事件内核对象 提醒同步以及交互
1 #include <Windows.h> 2 int main() 3 { 4 //异步操作最大的好处就是不会阻塞 5 HANDLE hFile = CreateFile(TEXT("Demo.txt"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, nullptr); 6 if (hFile != INVALID_HANDLE_VALUE) 7 { 8 //Read 9 BYTE bReadBuffer[100] = { 0 }; 10 OVERLAPPED oRead = { 0 }; 11 oRead.hEvent = CreateEvent(nullptr, TRUE, FALSE, TEXT("ReadEvent")); //事件内核对象 12 ReadFile(hFile, bReadBuffer, sizeof(bReadBuffer), nullptr, &oRead); 13 14 //Write 15 BYTE bWriteBuffer[10] = { 1,2,3,4,5,6,7,8,9,0 }; 16 OVERLAPPED oWrite = { 0 }; 17 oWrite.hEvent = CreateEvent(nullptr, TRUE, FALSE, TEXT("WriteEvent")); //事件内核对象 18 ReadFile(hFile, bWriteBuffer, sizeof(bWriteBuffer), nullptr, &oWrite); 19 20 //Do Same .... 21 //其他的线程 22 HANDLE hOverLapped[2] = { 0 }; 23 hOverLapped[0] = oRead.hEvent; 24 hOverLapped[1] = oWrite.hEvent; 25 26 while (true) 27 { 28 DWORD dwCase = WaitForMultipleObjects(2, hOverLapped, FALSE, INFINITE); 29 switch (dwCase - WAIT_OBJECT_0) 30 { 31 case 0: 32 //读完成 33 break; 34 case 1: 35 //写完成 36 break; 37 } 38 } 39 } 40 else 41 { 42 //GetLastError(); 43 } 44 45 return 0; 46 }
⊙ 可提醒的I/O 不可跨线程
1 #include <Windows.h> 2 3 VOID CALLBACK FileIOCompletionReadRoutine( 4 _In_ DWORD dwErrorCode, 5 _In_ DWORD dwNumberOfBytesTransfered, 6 _Inout_ LPOVERLAPPED lpOverladded 7 ) 8 { 9 MessageBox(nullptr, TEXT("Read"), TEXT("Read"), MB_OK); 10 } 11 12 int main() 13 { 14 //发送请求 15 //做自己的事情 16 //判断请求是否完成 17 18 //发送请求 -》完成后,操作系统提醒我 19 //可提醒I/0操作 20 //APC 21 //工厂(进程)-》工人(线程) 22 // APC机制 当线程空闲的时候(前提) -》 APC列表中的事情(自动执行) 23 // 线程为可提醒的窗台下 24 // 就是线程空闲的时候 25 //MessageBox -》 阻塞(闲下来) 不是可提醒状态 26 //Wait Sleep 函数 可提醒的状态 27 28 29 HANDLE hFile = CreateFile(TEXT("Demo.txt"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, nullptr); 30 31 if (hFile != INVALID_HANDLE_VALUE) 32 { 33 const UINT uLen = 255; 34 BYTE bReadBuf[uLen] = { 0 }; 35 OVERLAPPED oRead = { 0 }; 36 oRead.Offset = 5; 37 ReadFileEx(hFile, bReadBuf, uLen, &oRead, FileIOCompletionReadRoutine); 38 39 SleepEx(100, TRUE); 40 //DWORD WINAPI SleepEx( 41 // _In_ DWORD dwMilliseconds, 42 // _In_ BOOL bAlertable 43 // ); 44 45 //干自己的事情 Do Some...... 46 //运行程序 没有弹出消息框 47 //SleepEx Wait 可以使线程成为空闲状态 48 //while (10) 49 //{ 50 // Sleep(100); 51 //} 52 } 53 54 55 return 0; 56 }
时间: 2024-10-10 03:44:25