粗糙的完成端口映射简单测试小程序
#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;
}