异步IO

// 01 异步IO.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>

typedef struct _INFO
{
    HANDLE hFile;
    char* pbuf;
}INFO, *PINFO;
DWORD WINAPI ThreadProc(LPVOID param)
{
    PINFO pInfo = (PINFO)param;
    WaitForSingleObject(pInfo->hFile -1);
    printf("%d%d", (*(pInfo->pbuf)), (*(pInfo->pbuf+1)));
    return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE hFile =CreateFile(
        L"D:\\1.exe",            //文件路径
        GENERIC_READ | GENERIC_WRITE, //操作权限
        0,                                                        //共享方式
        NULL,                                                 //安全属性
        OPEN_EXISTING,                               //打开方式
        FILE_FLAG_OVERLAPPED,                 //最重要的!!!!已异步的方式打开一个文件
        NULL                                                   //没用
        );
    DWORD dwSize =  GetFileSize(hFile, NULL);                        //获取文件大小
    DWORD dwRubbish = 0;
    OVERLAPPED  ol = {};
    //ol.hEvent = CreateEvent(NULL, );//假如指定了设备对象,那么IO操作完成后,会将事件
                                                              //对象置为激发态,从而能够得到通知
    char* buf = new char[dwSize];

    DWORD m = ReadFile(hFile, buf, dwSize, &dwRubbish, &ol);
    INFO   info = { ol.hEvent, buf };
    HANDLE hThread = 
        CreateThread(NULL, NULL, ThreadProc, (LPVOID)&info, NULL,NULL);
    //...还有很多的代码

    //防止主线程退出
    WaitForSingleObject(hThread, -1);
    return 0;
}

 

posted @ 2016-03-24 21:27  天还是那么蓝  阅读(237)  评论(0编辑  收藏  举报