c++异步io学习笔记

// tr1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

HANDLE hFile = INVALID_HANDLE_VALUE;
struct MyOverlapped : public OVERLAPPED
{
	int total_size;
	DWORD file_size;
};
MyOverlapped o;
char g_chRead;
volatile DWORD g_Finished = 0;

HANDLE hEventRead = NULL;
HANDLE hEventWrite = NULL;

void CreateEvent()
{
	hEventRead = CreateEvent(NULL, TRUE, FALSE, NULL);
	hEventWrite = CreateEvent(NULL, TRUE, FALSE, NULL);
}
void CloseEvent()
{
	CloseHandle(hEventRead);
	hEventRead = NULL;
	CloseHandle(hEventWrite);
	hEventWrite = NULL;
}

void StartAsyncRead()
{
	hFile = CreateFile(L"D:\\NetFox.rar", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);

	if (hFile == INVALID_HANDLE_VALUE)
	{
		std::cout << "CreateFile failure.\n";
		return;
	}
	o.hEvent = hEventWrite;
	o.Offset = 0; // 从0开始读取
	o.file_size = GetFileSize(hFile, NULL);
	BOOL bRead = ReadFile(hFile, &g_chRead, 1, NULL, &o);
	if (bRead)
	{
		std::cout << "同步读取完成。\n";
	}
	else 
	{
		DWORD dwError = GetLastError();
		if (dwError == ERROR_IO_PENDING)
		{
			return;
		}
		else
		{
			cout << "异步读取文件失败。";
		}
	}
}
void OnReadFile()
{
	while (1)
	{
		WaitForSingleObject(hEventRead, INFINITE);
		ResetEvent(hEventWrite); //复位事件,需要测试如果不复位,系统会不会自动复位。
		ResetEvent(hEventRead); // 不允许再读取。由写入线程来触发。
		if (o.InternalHigh == 0)// 没有读取,可能是失败。
		{
			cout << "读取0字节,线程将退出。\n";
			InterlockedIncrement(&g_Finished);
			break;
		}

		o.total_size +=  o.InternalHigh;
		if (o.total_size >= o.file_size)
		{
			cout << "文件读取完毕,线程退出。\n";
			InterlockedIncrement(&g_Finished);
			break;
		}
		o.Offset = o.total_size;
		BOOL bRead = ReadFile(hFile, &g_chRead, 1, NULL, &o);
		if(bRead)
		{
			cout << "同步读取。\n";
		}
		else
		{
			DWORD dwError = GetLastError();
			if (dwError == ERROR_IO_PENDING)
			{
				continue;
			}
			else
			{
				cout << "文件读取或者失败。";
				InterlockedIncrement(&g_Finished);
				break;
			}
		}
	}
	cout << "读取线程退出。\n";
}
HANDLE g_hWriteFile = INVALID_HANDLE_VALUE;
void CreateWriteFile()
{
	g_hWriteFile = CreateFile(L"D:\\result.rar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	if(g_hWriteFile == INVALID_HANDLE_VALUE)
	{
		cout << "打开写文件失败。\n";
		return;
	}


}
void OnWriteFile()
{
	DWORD dwWrite = 0;
	while(1)
	{
		if (g_Finished)
		{
			break;
		}		
		WaitForSingleObject(hEventWrite, INFINITE);
		ResetEvent(hEventWrite);
		ResetEvent(hEventRead); // 没完成本次操作前禁止再读写。
		WriteFile(g_hWriteFile, &g_chRead, 1, &dwWrite, NULL);
		//cout << g_chRead;
		SetEvent(hEventRead);//触发读取线程。

	}
	cout << "写线程退出。\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
	ZeroMemory(&o, sizeof(o));
	CreateEvent();
	
	CreateWriteFile();
	StartAsyncRead();
	boost::thread_group works;
	works.create_thread(&OnWriteFile);
	works.create_thread(&OnReadFile);
	works.join_all();
	CloseEvent();
	CloseHandle(g_hWriteFile);
	CloseHandle(hFile);
	return 0;
}


你可能感兴趣的:(c++异步io学习笔记)