1. // 002_异步IO.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
    2. //
    3. #include <windows.h>
    4. #include <stdio.h>
    5. struct MyOverlapped : public OVERLAPPED {
    6. MyOverlapped()
    7. {
    8. // 将OVERLAPPED部分填充为0
    9. memset(this, 0, sizeof(OVERLAPPED));
    10. pBuff = NULL;
    11. }
    12. char *pBuff;
    13. ~MyOverlapped() {
    14. if (pBuff) {
    15. delete pBuff;
    16. }
    17. }
    18. };
    19. DWORD WINAPI ThreadProc(VOID* pArg)
    20. {
    21. MyOverlapped* pOv = (MyOverlapped*)pArg;
    22. WaitForSingleObject(pOv->hEvent,-1);
    23. printf("读取偏移:[%d]的IO任务完成, 实际读取到的字节数:%d"
    24. "读取到的内容是:%s",
    25. pOv->Offset,
    26. pOv->InternalHigh,
    27. pOv->pBuff);
    28. return 0;
    29. }
    30. int main()
    31. {
    32. HANDLE hFile = INVALID_HANDLE_VALUE;
    33. hFile = CreateFile(
    34. L"002_异步IO.cpp",
    35. GENERIC_READ,/*读写方式:只读*/
    36. FILE_SHARE_READ,/*共享方式: 共享读*/
    37. NULL,/*安全描述符*/
    38. OPEN_EXISTING,/*创建标志:存在时才打开*/
    39. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,/*文件属性和标志:正常属性|重叠IO标志 */
    40. NULL);
    41. MyOverlapped* ov = new MyOverlapped;
    42. ov->Offset = 0;// 表示从第20个字节开始读
    43. ov->pBuff = new char[200];
    44. memset(ov->pBuff, 0, 200);
    45. DWORD read = 0;
    46. ov->hEvent = CreateEvent(NULL,/*安全描述符*/
    47. FALSE,/*是否需要手动重置信号*/
    48. FALSE,/*初始是否有信号*/
    49. NULL/*事件对象名(一般为了跨进程使用)*/);
    50. ReadFile(hFile, ov->pBuff, 100, &read, ov);
    51. MyOverlapped* ov2 =new MyOverlapped;
    52. ov2->Offset = 100;
    53. ov2->hEvent = CreateEvent(NULL,/*安全描述符*/
    54. FALSE,/*是否需要手动重置信号*/
    55. FALSE,/*初始是否有信号*/
    56. NULL/*事件对象名(一般为了跨进程使用)*/);
    57. ov2->pBuff = new char[200];
    58. memset(ov2->pBuff, 0, 200);
    59. ReadFile(hFile, ov2->pBuff,100, &read, ov2);
    60. CreateThread(0, 0, &ThreadProc, ov2, 0, 0);
    61. CreateThread(0, 0, &ThreadProc, ov, 0, 0);
    62. while ( 1 )
    63. {
    64. Sleep(100);
    65. }
    66. }