这是阻止代码,如何将其转换为非阻塞异步? 我正在尝试在客户端和服务器之间进行异步通信。 这是我的阻塞同步代码,我该怎么做异步?
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;
}
答案 0 :(得分:0)
将while循环移到函数本身之外:
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
}
你的主循环得到了while循环
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
}