Search code examples
c++ogr

Converting blocking synchronous code to async


that is the blocking code, how would I convert it to non blocking async ? I'm trying to do async communication between a client and a server. here is my blocking sync code, how would I do it async ?

bool S3W::CImplServerData::WaitForCompletion(unsigned int timeout)
{


    unsigned int t1;
    while (true)
    {
        BinaryMessageBuffer currBuff;
        if (m_Queue.try_pop(currBuff))
        {
            ProcessBuffer(currBuff);
             t1 = clock();
        }
        else
        {
            unsigned int  t2 = clock();

            if ((t2 - t1) > timeout)
            {
                return false;
            }
            else
            {
                Sleep(1);
            }
        }
    }

    return true;
}

Solution

  • Move the while loop outside of the function itself:

    bool S3W::CImplServerData::WaitForCompletion()
    {
        BinaryMessageBuffer currBuff;
        if (m_Queue.try_pop(currBuff))
        {
            ProcessBuffer(currBuff);
            // do any processing needed here
        }
    
        // return values to tell the rest of the program what to do
    }
    

    your main loop gets the while loop

    while (true)
    {
        bool outcome = S3W::CImplServerData::WaitForCompletion()
    
        // outcome tells the main program whether any communications
        // were received. handle any returned values here
    
        // handle stuff you do while waiting, e.g. check for input and update 
        // the graphics
    }