【Windows原理】线程池-异步IO完成时调用

// 03.线程池_异步IO完成时调用-复习.cpp : 定义控制台应用程序的入口点。
//

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

struct MyOVERLAPPED :public OVERLAPPED
{
public:
	char * pBuff;
	int nIndex;
	MyOVERLAPPED();
	MyOVERLAPPED(int nSize, int nFileOffsetLow, int nFileOffsetHight = 0);
	~MyOVERLAPPED();
};

// 默认构造函数
MyOVERLAPPED::MyOVERLAPPED() :pBuff(NULL)
{
	OVERLAPPED::hEvent = 0;
}

MyOVERLAPPED::MyOVERLAPPED(int nIoSize, int nFileOffsetLow, int nFileOffsetHight)
{
	OVERLAPPED::hEvent = 0;
	OVERLAPPED::Offset = nFileOffsetLow;
	OVERLAPPED::OffsetHigh = nFileOffsetHight;
	pBuff = new char[nIoSize];
}

MyOVERLAPPED::~MyOVERLAPPED()
{
	if (pBuff != NULL)
	{
		delete[] pBuff;
		pBuff = NULL;
	}
}


VOID WINAPI IODoneCallback(
	PTP_CALLBACK_INSTANCE Instance, 
	PVOID Context, PVOID Overlapped, 
	ULONG IoResult,// 错误码
	ULONG_PTR NumberOfBytesTransferred,// 读写完成个数
	PTP_IO Io)
{
	MyOVERLAPPED * pMyOverlapped = (MyOVERLAPPED*)Overlapped;
	printf("[%d] IO任务完成,读取字节:%d,位置:%d 内容:【%s】",pMyOverlapped->nIndex,pMyOverlapped->InternalHigh,pMyOverlapped->Offset,pMyOverlapped->pBuff);

	delete pMyOverlapped;
}

int _tmain(int argc, _TCHAR* argv[])
{

	HANDLE hFile = CreateFile(L"1.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);

	// 将文件对象和线程池关联
	PTP_IO hPool = CreateThreadpoolIo(hFile, IODoneCallback, 0, 0);

	// 使用线程池等待一个IO任务完成
	// 每次在发出IO操作前都要调用一次
	StartThreadpoolIo(hPool);
	DWORD dwWrite;
	MyOVERLAPPED *ov = new MyOVERLAPPED(200,0);
	ov->nIndex = 1;

	// 开始读文件,读200字节
	ReadFile(hFile, ov->pBuff, 200, &dwWrite, ov);
	
	// 又一次IO任务,所以需要重新启动
	StartThreadpoolIo(hPool);
	DWORD dwWrite1;
	MyOVERLAPPED *ov1 = new MyOVERLAPPED(400, 0);
	ov1->nIndex = 2;

	// 开始读文件,读400字节
	ReadFile(hFile, ov1->pBuff, 400, &dwWrite1, ov1);
	Sleep(1000);
	// 解除文件与线程池的关联
	CloseThreadpoolIo(hPool);
	// 关闭句柄
	CloseHandle(hFile);

	return 0;
}

 

文 / luna
LEAVE A REPLY

loading