Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 如何打印()STD::THEXTHYT::C++中的GETSyId()_Multithreading_C++11 - Fatal编程技术网

Multithreading 如何打印()STD::THEXTHYT::C++中的GETSyId()

Multithreading 如何打印()STD::THEXTHYT::C++中的GETSyId(),multithreading,c++11,Multithreading,C++11,我试着将其转换为void*并使用%p。我还尝试过使用%lx格式的intptr\t。两次我都得到无效的强制转换错误 我使用-Wall-Werror检查printf的参数是否与函数的格式字符串匹配。因此,我不能仅仅指望get_id在堆栈上留下一个4或8字节的值,然后简单地将该值打印为十六进制 我使用的是gcc版本9.2.1 20190827 Red Hat 9.2.1-1 gcc 操作系统是Fedora 31三十一版。CPU为64位Intel x86。使用流: std::ostringstream

我试着将其转换为void*并使用%p。我还尝试过使用%lx格式的intptr\t。两次我都得到无效的强制转换错误

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

我使用的是gcc版本9.2.1 20190827 Red Hat 9.2.1-1 gcc

操作系统是Fedora 31三十一版。CPU为64位Intel x86。

使用流:

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

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

我能够在具有类似要求的日志功能中使用这种变通方法:

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类型非常不透明。

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

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类型非常不透明。

这对于获取\u id返回引用的对象类型应该很有帮助。但是为什么要在C++程序中使用PROTF?这是GETHYID返回引用的对象的类型应该有帮助。但是为什么你想在C++程序中使用PROTF呢?或者仅仅使用STD::CUT代替PROTF。尽管STD::Endl看起来有点不必要。唉,不能用cout。确切地说,实际问题不是printf,而是基于vsnprintf的日志函数。考虑到系统的范围,重写该函数以模拟iostreams的可能性为零。@SwissFrank:您可能需要阅读std::streambuf。您可以交换std::cout/std::cerr下面的streambuf,然后您的自定义streambuf可以调用log_printf%s,buf。或者只使用std::cout而不是printf。我投了票,尽管std::endl似乎有点不必要唉,不能用cout。确切地说,实际问题不是printf,而是基于vsnprintf的日志函数。考虑到系统的范围,重写该函数以模拟iostreams的可能性为零。@SwissFrank:您可能需要阅读std::streambuf。您可以交换std::cout/std::cerr下面的streambuf,然后您的自定义streambuf可以调用log_printf%s,buf。