// Test32.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <process.h>
#include <iostream>
HANDLE m_hCompletionPort;
volatile BOOL m_bShutDown;
struct TESTOVERLAPPED
{
OVERLAPPED m_ol;
CHAR szData[512];
};
UINT WINAPI IOWorkerThreadProc(LPVOID pParam)
{
BOOL bError = FALSE;
DWORD dwIoSize = 0;
DWORD dwCmpKey = 0;
LPOVERLAPPED lpOverlapped = NULL;
TESTOVERLAPPED* pOverlapBuff = NULL;
while ( !bError )
{
pOverlapBuff = NULL;
dwCmpKey = 0;
// Get a completed IO request.
BOOL bIORet = GetQueuedCompletionStatus(m_hCompletionPort, &dwIoSize, (LPDWORD) &dwCmpKey, &lpOverlapped, INFINITE);
// Simulate workload (for debugging, to find possible reordering)
//Sleep(20);
// If Something whent wrong..
if (!bIORet)
{
DWORD dwIOError = GetLastError();
if(dwIOError != WAIT_TIMEOUT) // It was not an Time out event we wait for ever (INFINITE)
{
continue;
}
}// if (!bIORet)
if(bIORet && lpOverlapped && dwCmpKey)
{
pOverlapBuff=CONTAINING_RECORD(lpOverlapped, TESTOVERLAPPED, m_ol);
if(pOverlapBuff!=NULL)
{
//pThis->ProcessIOMessage(pOverlapBuff, dwCmpKey, dwIoSize);
printf("ThreaId:0x%x %d %s ",GetCurrentThreadId(),dwCmpKey,pOverlapBuff->szData);
}
delete pOverlapBuff;
}
if((dwCmpKey == NULL) && (pOverlapBuff == NULL) && m_bShutDown)
{
bError = TRUE;
}
}
printf("Thread dead!");
return 0xdead;
}
int _tmain(int argc, _TCHAR* argv[])
{
m_hCompletionPort = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 0 );
uintptr_t hThread =_beginthreadex(0,0,IOWorkerThreadProc, 0,0, NULL);
hThread =_beginthreadex(0,0,IOWorkerThreadProc, 0,0, NULL);
hThread =_beginthreadex(0,0,IOWorkerThreadProc, 0,0, NULL);
m_bShutDown = FALSE;
for(int i = 0; i < 30; i++)
{
DWORD dwCmpKey = i;
TESTOVERLAPPED * pOverlapBuff = new TESTOVERLAPPED;
memset(pOverlapBuff->szData,0,sizeof(pOverlapBuff->szData));
sprintf(pOverlapBuff->szData,"CMD ID:%d",i);
PostQueuedCompletionStatus(m_hCompletionPort, 0, (ULONG_PTR) &dwCmpKey, &pOverlapBuff->m_ol);
}
m_bShutDown = TRUE;
PostQueuedCompletionStatus(m_hCompletionPort,0,0,0);
getchar();
return 0;
}