6
Dec
0

C++ – OpenMP – std::cout – Print with OpenMP

In this post I propose a simple class to print using cout in a program that uses OpenMP.
Of course you can use a mutex to protect the cout stream, but I prefer to use a buffer before printing as I show in this example.

The Code

#include <iostream>
#include <sstream>

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

Use it as …

// We create a temporary variable
// That is not very efficiency, but if you are printing you may not look to efficiency
std::cout << (ParallelStream() <<"I am " << omp_get_thread_num() << " working at section 3\n").toString();//<< std::endl;

//...

The next Method is old and depreciated

The code

#include <iostream>
#include <sstream>

#include <omp.h>

/**
* This class is a buffer to print using std::cout
* in parallel
*/
class Cout_MP{
private:
	// Buffer
	std::ostringstream oss;
	// private constructor
	Cout_MP(): oss(std::ostringstream::out){
	}
public:
	// to get a printer
	static Cout_MP Print(){
		return Cout_MP();
	}

	// for all types (except Action)
	template <class T>
	Cout_MP& operator<<(const T& input){
		oss << input;
		return *this;
	}

	// actions
	enum Action{
		ENDL,
		PRINT,
	};
	// for action type
	Cout_MP& operator<<(const Action& input){
		switch(input){
			// endl => append \n
			case ENDL:{
				oss << "\n";
			}
		    // endl or print => print
			case PRINT:{
				std::cout << oss.str();
				std::cout.flush();
				oss.clear();
			}break;
		}
		return *this;
	}
};

// Example
int _tmain(int argc, _TCHAR* argv[])
{
	std::cout << "Basic std::cout" << std::endl;
	#pragma omp parallel num_threads(4)
	{
		std::cout << "I want " << "to print many " << "things " << "thread : " << omp_get_thread_num() << std::endl;
	}

	std::cout << "With Cout_MP" << std::endl;
	#pragma omp parallel num_threads(4)
	{
		Cout_MP::Print() << "I want " << "to print many " << "things " << "thread : " << omp_get_thread_num() << Cout_MP::ENDL;
	}

	return 0;
}

Output

Basic std::cout
I want I want I want I want to print many to print many to print many to print m
any things things things things thread : thread : thread : thread : 0132

With Cout_MP
I want to print many things thread : 3
I want to print many things thread : 0
I want to print many things thread : 2
I want to print many things thread : 1
Appuyez sur une touche pour continuer...
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.

Comments are closed.

Celadon theme by the Themes Boutique