multiple threads writing to std::cout or std::cerr

前端 未结 4 1359
醉话见心
醉话见心 2020-12-14 20:52

I have OpenMP threads that write to the console via cout and cerr. This of course is not safe, since output can be interleaved. I could do something like

#pr         


        
4条回答
  •  天命终不由人
    2020-12-14 20:58

    You can use an approach similar to a string builder. Create a non-template class that:

    • offers templated operator<< for insertion into this object
    • internally builds into a std::ostringstream
    • dumps the contents on destruction

    Rough approach:

     class AtomicWriter {
        std::ostringstream st;
     public:
        template  
        AtomicWriter& operator<<(T const& t) {
           st << t;
           return *this;
        }
        ~AtomicWriter() {
           std::string s = st.str();
           std::cerr << s;
           //fprintf(stderr,"%s", s.c_str());
           // write(2,s.c_str(),s.size());
        }
     };
    

    Use as:

    AtomicWriter() << "my variable: " << variable << "\n";
    

    Or in more complex scenarios:

    {
       AtomicWriter w;
       w << "my variables:";
       for (auto & v : vars) {
          w << ' ' << v;
       }
    }  // now it dumps
    

    You will need to add more overloads if you want manipulators, you can use write better than fprintf for the atomic write in the destructor, or std::cerr, you can generalize so that the destination is passed to the constructor (std::ostream/file descriptor/FILE*),

提交回复
热议问题