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

前端 未结 4 1361
醉话见心
醉话见心 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 21:07

    I don't have enough reputation to post a comment, but I wanted to post my addition to the AtomicWriter class to support std::endl and allow for other streams to be used besides std::cout. Here it is:

    class AtomicWriter {
        std::ostringstream st;
        std::ostream &stream;
    public:
        AtomicWriter(std::ostream &s=std::cout):stream(s) { }
        template 
        AtomicWriter& operator<<(T const& t) {
            st << t;
            return *this;
        }
        AtomicWriter& operator<<( std::ostream&(*f)(std::ostream&) ) {
            st << f;
            return *this;
        }
        ~AtomicWriter() { stream << st.str(); }
    };
    

提交回复
热议问题