// 002_异步IO.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <windows.h>
#include <stdio.h>
struct MyOverlapped : public OVERLAPPED {
MyOverlapped()
{
// 将OVERLAPPED部分填充为0
memset(this, 0, sizeof(OVERLAPPED));
pBuff = NULL;
}
char *pBuff;
~MyOverlapped() {
if (pBuff) {
delete pBuff;
}
}
};
DWORD WINAPI ThreadProc(VOID* pArg)
{
MyOverlapped* pOv = (MyOverlapped*)pArg;
WaitForSingleObject(pOv->hEvent,-1);
printf("读取偏移:[%d]的IO任务完成, 实际读取到的字节数:%d"
"读取到的内容是:%s",
pOv->Offset,
pOv->InternalHigh,
pOv->pBuff);
return 0;
}
int main()
{
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile(
L"002_异步IO.cpp",
GENERIC_READ,/*读写方式:只读*/
FILE_SHARE_READ,/*共享方式: 共享读*/
NULL,/*安全描述符*/
OPEN_EXISTING,/*创建标志:存在时才打开*/
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,/*文件属性和标志:正常属性|重叠IO标志 */
NULL);
MyOverlapped* ov = new MyOverlapped;
ov->Offset = 0;// 表示从第20个字节开始读
ov->pBuff = new char[200];
memset(ov->pBuff, 0, 200);
DWORD read = 0;
ov->hEvent = CreateEvent(NULL,/*安全描述符*/
FALSE,/*是否需要手动重置信号*/
FALSE,/*初始是否有信号*/
NULL/*事件对象名(一般为了跨进程使用)*/);
ReadFile(hFile, ov->pBuff, 100, &read, ov);
MyOverlapped* ov2 =new MyOverlapped;
ov2->Offset = 100;
ov2->hEvent = CreateEvent(NULL,/*安全描述符*/
FALSE,/*是否需要手动重置信号*/
FALSE,/*初始是否有信号*/
NULL/*事件对象名(一般为了跨进程使用)*/);
ov2->pBuff = new char[200];
memset(ov2->pBuff, 0, 200);
ReadFile(hFile, ov2->pBuff,100, &read, ov2);
CreateThread(0, 0, &ThreadProc, ov2, 0, 0);
CreateThread(0, 0, &ThreadProc, ov, 0, 0);
while ( 1 )
{
Sleep(100);
}
}