c++ - std::cout 线程安全格式化和 io 操作

标签 c++ multithreading iostream

想象一下你有两个线程。第一个线程尝试使用 std::dec 将整数打印为十进制:

std::cout << std::dec << 123 << std::endl;
第二个线程尝试使用 std::hex 将整数打印为十六进制。 :
std::cout << std::hex << 0x321 << std::endl;
是否保证 123 将打印为十进制而 0x321 将打印为十六进制?如果不是,我该如何正确处理std::cout在多线程环境中格式化?
C++20 有 std::osyncstream .但是在 C++20 之前我们可以使用什么?

最佳答案

从一开始,这不是 std::cout 的选项。 .
如果您只想使用不同的对象,那么简单的方法就是对所需的每个“复合”使用 stringstream,例如:

std::cout << (std::ostringstream{} << std::hex << 0x321 << std::endl).str();
或者,您可以创建自己的流类,将所有内容转发到 std::cout销毁时(例如,您可以拥有 std::ostringstream 作为成员或继承它):
~MyStringStream(){
  std::cout << str();
}

我不建议在实际的 std::cout 上更改这个事实因为别人不会期待std::cout以这种或那种不同的方式行事。然而话虽如此,我认为重定向是可能的,所以我创造了一种方式来展示这一点(有点像黑客:我认为所有做这样的事情都是黑客)以及如何使这成为可能。请注意,这根本不是一个完整的解决方案,它只是展示了如何获得 std::cout通过您自己的流类,然后需要“正确”实现/覆盖,使线程安全,然后添加必要的同步,或者您计划获得额外的级别等。另请注意我没有考虑到这如何干扰 std::cout捆绑流(例如 std::instd::err ),但我想这没什么大不了的。
Try it yourself on godbolt
#include <utility>
#include <string>
#include <iostream>
#include <sstream>


std::stringstream new_out;

class SyncedStreamBuf : public std::stringbuf {
public:
  SyncedStreamBuf(){}
  

  virtual int sync() override {
    new_out << "From override: " << str();
    str("");//empty buffer
    return 0;//success
  }
};

class SyncedStream : public std::ostream {
public:
  SyncedStream() : std::ostream(&syncedStreamBuf_){
  }

private:
  SyncedStreamBuf syncedStreamBuf_;
};

SyncedStream my_stream;

int main()
{
    std::streambuf* cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer
 
    std::cout.rdbuf(my_stream.rdbuf());//redirect cout to our own 'stuff'
    
    static_cast<std::ostream&>(new_out).rdbuf(cout_buff);//put cout's buffer into a new out stream
    
    
    new_out << "test: new_out now prints to stdout\n";
    std::cout << "some message\n";//<--now goes through our overridden class
    std::cout.flush();

    std::cout << "you will see this message - didn't flush\n";
}
输出:
test: new_out now prints to stdout

From override: some message

关于c++ - std::cout 线程安全格式化和 io 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63376709/

相关文章:

python - Visual Studio,Marmalde C++ : import libpython. a,在 arm 上的嵌入式解释器中运行 python 代码

multithreading - 这段代码中是否存在潜在的饥饿问题,或者只是我?

c++ - 如何使用同一个函数C++实例化多个线程

c++ - fatal error C1075 : end of file found before the left brace and read and write files not working

c++ - 为什么空 streambuf 的流插入失败?

python - 将 argv 的元素复制到新数组中

c# - 如何使用 C++/CLI Wrapper 将变量参数从托管传递到非托管?

C++ 用私有(private)变量定义 IO 成员变量

java - 如何防止关闭钩子(Hook)陷入死锁?

c++ - namespace 检测