【问题标题】:how to printf() std::this_thread::get_id() in C++?如何在 C++ 中 printf() std::this_thread::get_id()?
【发布时间】:2020-04-14 08:35:17
【问题描述】:

我尝试转换为 void* 并使用 %p。我也试过intptr_t,格式为%lx。两次我都收到“无效的演员表”错误。

我正在使用-Wall -Werror,它检查printf() 的参数是否与函数的格式字符串匹配。所以我不能仅仅指望get_id() 在堆栈上留下一个 4 或 8 字节的值,然后简单地将该值打印为十六进制。

我正在使用 gcc 版本 9.2.1 20190827 (Red Hat 9.2.1-1) (GCC)

操作系统是 Fedora release 31 (31) 。 CPU 是 64 位 Intel x86。

【问题讨论】:

  • 这个std::thread::idget_id 返回的对象的类型)参考应该很有帮助。但是为什么要在 C++ 程序中使用printf

标签: multithreading c++11


【解决方案1】:

使用流:

std::ostringstream oss;
oss << std::this_thread::get_id() << std::endl;
printf("%s\n", oss.str().c_str());

【讨论】:

  • 或者只使用std::cout 而不是printf
  • 得到了我的投票,尽管std::endl 似乎有点不必要。 :)
  • 唉,不能使用 cout。确切地说,实际问题不是 printf(),而是基于 vsnprintf() 的日志记录函数。鉴于系统的范围,重写该函数以模拟 iostreams 的机会为零。
  • @SwissFrank:您可能需要阅读std::streambuf。你可以换掉std::cout/std::cerr下面的streambuf,然后你的自定义streambuf就可以调用log_printf("%s", buf)
【解决方案2】:

我能够在具有类似要求的日志记录功能中使用此解决方法:

static std::ostringstream id;
static std::string sid = id.str();

if (sid.empty())
{
    id << std::this_thread::get_id();
    sid = id.str();
}

// our code actually has a vsnprintf() 
printf("[%u:%s] %s", getpid(),  
        sid.c_str(), another_string ); 

与答案 1 相同的机制。线程 id 类型非常不透明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2011-05-25
    相关资源
    最近更新 更多