Last Updated: February 25, 2016
· dawehner

cout output in openMP

If you parallalized your code with openMP you soon will realize that using std::cout will
not work as the strings from the other threads might output at the same time.

One solution is to use a mutex before the output, but this is not really elegant.
An alternative solution is to store the string you want to output in a buffer.

class ParallelStream{
    std::ostringstream stdStream;
    template <class T>
    ParallelStream& operator<<(const T& inData){
        stdStream << inData;
        return *this;
    std::string toString() const{
        return stdStream.str();

#pragma omp parallel for
for (int n_radial = 0; n_radial < Nradial; n_radial++) {
  // Note: The string is first collected into the ParallelStream object and then moved into the output.
  cout << (ParallelStream() << n_radial << " (" << Nradial << ")").toString() << endl;