Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::cout thread safe formatting and io manipulation

Imagine you have two threads. The first thread tries to print integer as decimal using std::dec:

std::cout << std::dec << 123 << std::endl;

The second thread tries to print integer as hexadecimal using std::hex:

std::cout << std::hex << 0x321 << std::endl;

Is it guaranteed that 123 will be printed as decimal and 0x321 will be printed as hexadecimal? If it is not, how do I do proper std::cout formatting in multithread environment?

C++20 has std::osyncstream. But what can we use before C++20?

like image 290
anton_rh Avatar asked Aug 12 '20 12:08

anton_rh


People also ask

Is std :: cout safe?

A side note: std::cout is thread-safe The C++11 standard guarantees, that you must not protect the single characters, written to std::cout. Each character will atomically be written. Of course, it is possible, that more output statements like in the example will interleave. But that is only an optical issue.

Is std :: out thread-safe?

std::cout is already thread-safe.

How do you ensure thread safety in C++?

An object is thread-safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously. If an object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected.


1 Answers

From the get-go, this isn't an option with std::cout.

If you just want to use a different object a simpel way is just use stringstream for each 'compound' needed eg.:

std::cout << (std::ostringstream{} << std::hex << 0x321 << std::endl).str();

Alternatively you can make your own stream class that just forwards everything to std::cout on destruction (eg. you could have std::ostringstream as a member or inherit it):

~MyStringStream(){
  std::cout << str();
}

I wouldn't recommend changing this fact on the actual std::cout because others will not expect std::cout to behave in this or that different way. However with that being said I think it is possible with redirection, so I created a way to showcase this (somewhat of a hack: I consider everything that does something like this a hack) and how to make this possible. Please note this isn't a finished solution at all, it just shows how to get std::cout to go through your own stream class, which then needs to be implemented/overridden 'correctly', made thread-safe and then added the neccesary synchronizations, or however you plan to get that extra level, etc. Please also note I haven't considered how this interferes with the std::cout tie'ed streams (eg. std::in, std::err), but I guess it's not a big deal.

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

Output:

test: new_out now prints to stdout

From override: some message
like image 192
darune Avatar answered Oct 09 '22 01:10

darune