粗糙的完成端口映射简单测试小程序

粗糙的完成端口映射简单测试小程序

#include <conio.h>
#include <list>
#include <windows.h>
#include <process.h>
#include <iostream>
enum
{
	IocpListEmpty,
	IocpListPush,
	IocpListPop
};
typedef struct IocpParam
{
	int nOperator;//操作
	std::string strData;//数据
	_beginthread_proc_type cbFunc;//回调
	IocpParam(int op, const char* sData, _beginthread_proc_type cb = NULL)
	{
		nOperator = op;
		strData = sData;
		cbFunc = cb;
	}
	IocpParam()
	{
		nOperator = -1;
	}
}IOCP_PARAM;

void threadmain(HANDLE hIOCP)
{
	std::list<std::string> lstString;
	DWORD dwTransferred = 0;
	ULONG_PTR CompletionKey = 0;
	OVERLAPPED* pOverlapped = NULL;
	while (GetQueuedCompletionStatus(hIOCP, &dwTransferred, &CompletionKey, &pOverlapped, INFINITE))
	{
		if ((dwTransferred == 0) || (CompletionKey == NULL))
		{
			printf("thread is prepare to exit!\r\n");
			break;
		}
		IOCP_PARAM* pParam = (IOCP_PARAM*)CompletionKey;
		if (pParam->nOperator == IocpListPush)
		{
			lstString.push_back(pParam->strData);
		}
		else if (pParam->nOperator == IocpListPop)
		{
			std::string str;
			if (lstString.size() > 0)
			{
				str = lstString.front();
				lstString.pop_front();
			}
			if (pParam->cbFunc)
			{
				pParam->cbFunc(&str);
			}
		}
		else if (pParam->nOperator == IocpListEmpty)
		{
			lstString.clear();
		}
		delete pParam;
	}
}

void threadQueueEntry(HANDLE hIOCP)
{
	threadmain(hIOCP);
	_endthread();
}
void func(void* arg)
{
	std::string* pstr = (std::string*)arg;
	if (pstr != NULL)
	{
		printf("pop from list:%s\r\n", pstr->c_str());
		//delete pstr;
	}
	else
	{
		printf("list is empty!\r\n");
	}
}

int main()
{
	printf("press any key to exit....\r\n");
	HANDLE hIOCP = INVALID_HANDLE_VALUE;// I/O Completion Port
	hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1);
	if (hIOCP == INVALID_HANDLE_VALUE || (hIOCP == NULL))
	{
		printf("create iocp failed!%d\r\n", GetLastError());
		return 1;
	}
	HANDLE hThread = (HANDLE)_beginthread(threadQueueEntry, 0, hIOCP);
	ULONGLONG tick = GetTickCount64();
	ULONG_PTR tick0 = GetTickCount64();
	while (_kbhit() == 0)
	{
		if (GetTickCount64() - tick0 > 1300)
		{//取
			PostQueuedCompletionStatus(hIOCP, sizeof(IOCP_PARAM), (ULONG_PTR)new IOCP_PARAM(IocpListPop, "hello world!",func), NULL);
			tick0 = GetTickCount64();
		}
		if (GetTickCount64() - tick > 2000)
		{//写
			PostQueuedCompletionStatus(hIOCP, sizeof(IOCP_PARAM), (ULONG_PTR)new IOCP_PARAM(IocpListPush, "hello world!"), NULL);
			tick = GetTickCount64();		}
		Sleep(1);
	}
	if (hIOCP != NULL)
	{
		PostQueuedCompletionStatus(hIOCP, 0, NULL, NULL);
		WaitForSingleObject(hThread, INFINITE);
	}
	CloseHandle(hIOCP);
	exit(0);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值