010 異步I/O處理 002
阿新 • • 發佈:2017-05-28
bool 處理 error let adf 自己 eof multipl same
● 異步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 }
010 異步I/O處理 002