IOCP GetQueuedCompletionStatus多线程切换的不确定性

#include
#include
#include
#include
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 main(int argc, CHAR* argv[])
{
    m_hCompletionPort = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 0 );
    unsigned long 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, (DWORD) &dwCmpKey, &pOverlapBuff->m_ol);
    }
    m_bShutDown = TRUE;
    PostQueuedCompletionStatus(m_hCompletionPort,0,0,0);
    getchar();
    return 0;
}

运行程序结果,可以证明:对于每个PostQueuedCompletionStatus的投递,GetQueuedCompletionStatus的返回是线程不可预知

你可能感兴趣的:(多线程,null)