C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C异步OutputDebugString大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
使用c 11中的新std :: async,我想我可能会尝试实现OutputDebugString的异步版本,以免我通过通常的OutputDebugString函数通常对每个小细节进行大量打印而导致性能降低. .

所以这是我原来的同步OutputDebugString实现(可行):

static void OutputDebugStringN(const char *format,...)
{
    char outstring[256];
    memset(outstring,sizeof(outstring));

    try
    {
        va_list args = {0};
        va_start(args,format); //args = (va_list) (&format+1);

        vsprintf_s(outstring,format,args);

        va_end(args);

        OutputDebugString(outstring);
    }
    catch (...) //most likely reference val arg error (va_list doesn't support ref args)
    {
        OutputDebugString("[OutputDebugStringN] Something went wrong\n");
    }
}

以及我对非同步版本的非常小的尝试(不起作用):

static void OutputDebugStringN(const char *format,...)
{
    auto future = std::async([]{
        char outstring[256];
        memset(outstring,sizeof(outstring));
        try
        {
            va_list args = {0};
            va_start(args,format); //args = (va_list) (&format+1);

            vsprintf_s(outstring,args);

            va_end(args);

            OutputDebugString(outstring);
        }
        catch (...) //most likely reference val arg error (va_list doesn't support ref args)
        {
            OutputDebugString("[OutputDebugStringN] Something went wrong\n");
        }
    }); 
}

由于上述方法不起作用,我现在开始认为异步调用OutputDebugStringN可能比尝试在函数内部启动异步作业更好(这很有用,但很麻烦):

auto dstring = std::async([]{ OutputDebugStringN("[NovelScript::ParseTokens] searched bookmark: \"%s\" does not exist\n",bookmark.c_str());} );

所以这里有两个我想问的问题:

>我应该如何实现OutputDebugString的异步版本?
>我是否应该尝试实现OutputDebugString的异步版本?

对上述代码和任何其他评论的批评也非常受欢迎.

解决方法

我认为你应该为你的消息设置一个队列,而不是每次调用你的函数都启动一个线程,这样你的消息将以正确的顺序输出干净.

所以你的功能例如OutputDebugStringN(const char * format,…)将创建消息字符串,然后对单独的打印输出线程从中读取的字符串进行排队.该线程将调用OutputDebugString.

这是一个例子 – 虽然不完整,但是不应该修改错误处理和print_from_queue直到某些终止条件运行并且对cpu更加友好.

std::mutex g_m;
std::deque<std::string> que;
std::atomic<bool> endcond = false;

void queue(std::string msg)
{
  std::lock_guard<mutex> _(g_m);
  que.push_back(msg);
}

void print_from_queue()
{
  while ( !endcond )
  {
    if ( que.size() )
    {
      std::lock_guard<mutex> _(g_m);
      std::string msg = que.front();
      que.pop_front();
      OutputDebugStringA(msg.c_str());
    }
  }
}

int debugf( const char *format,... )
{
  std::vector<char> line(256);
  va_list args;
  va_start( args,format );
  int len = vsprintf_s( &line[0],line.size(),args );
  va_end( args );
  queue( &line[0] );
  return len;
}

int _tmain(int argc,_TCHAR* argv[])
{
  auto thr = std::async( std::launch::async,print_from_queue );
  debugf("message1");
  debugf("message2");
...

大佬总结

以上是大佬教程为你收集整理的C异步OutputDebugString全部内容,希望文章能够帮你解决C异步OutputDebugString所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:异步