将阻塞同步代码转换为异步代码
Converting blocking synchronous code to 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;
}
将 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
}
那是阻塞代码,我如何将它转换为非阻塞异步? 我正在尝试在客户端和服务器之间进行异步通信。 这是我的阻塞同步代码,我该怎么做异步?
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;
}
将 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
}