2017-03-06 61 views
0

即阻塞代码,我将如何将其转换为非阻塞异步? 我试图做一个客户端和服务器之间的异步通信。 这里是我的阻止同步代码,我将如何做到异步?将阻塞同步代码转换为异步

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

你怎么做的 “沟通”?你在使用特定的框架吗?一些平台特定的功能?请详细说明!请花一些时间[阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask),并学习如何创建[最小,完整和可验证示例](http: //stackoverflow.com/help/mcve)。 –

+0

我正在使用OGR Api。我将编辑我的帖子 –

回答

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 
} 
+0

这是异步通信?所以它没有太多的代码应该重写? –

+0

顺便说一句,你可以去多线程,但这是这样的东西矫枉过正。你已经有try_pop这是一个非阻塞函数来检查输入,所以你可以利用它来解决阻塞问题。这是你在单线程应用程序中如何做到的。 –

+0

非常感谢! –