【问题标题】:Converting blocking synchronous code to async将阻塞同步代码转换为异步
【发布时间】:2023-03-12 12:13:02
【问题描述】:

这是阻塞代码,我如何将其转换为非阻塞异步? 我正在尝试在客户端和服务器之间进行异步通信。 这是我的阻塞同步代码,我将如何异步执行?

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;
}

【问题讨论】:

标签: c++ ogr


【解决方案1】:

将 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
}

【讨论】:

  • 这是异步通信吗?所以不需要重写那么多代码?
  • 顺便说一句,您可以使用多线程,但这对于这样的事情来说太过分了。您已经有了 try_pop,它是一个用于检查输入的非阻塞函数,因此您可以利用它来解决阻塞问题。这就是您在单线程应用程序中执行此操作的方式。
  • 是否应该在自己的线程和另一个线程中调用 while(true){WaitForCompletion()} 来将数据推送到队列中?
  • 我真的不建议为此使用线程。在您的程序中,无论如何您都需要一个主循环。在主循环中,您完成所有“家务”。检查键盘+鼠标输入,检查传入消息,更新图形,更新逻辑代码等。基本上将它们全部设计为非阻塞代码。如果您为此使用线程,那么它对您来说将是一个巨大的 PITA。
  • 顺便说一句,您以后在处理繁重的处理时只想考虑线程。然后你会有一个线程来处理键盘/鼠标/消息等,并有单独的线程来进行数字运算。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 2015-10-24
  • 2013-05-07
相关资源
最近更新 更多