I've looked everywhere for an example and checked the C++ manual (I learn best by example).
What I need is a method that can write to standard out with blocking for a concurrent assignment.
I was suggested to use "protected cout" but I have no idea what is meant by that. Originally I've been using's C's write but I lose a few points for doing this.
Other solutions I thought of was using a semaphore to protect cout, so it can only print for one thread at a time. But I get the feeling that there's a built in one for C++ somewhere out there...
Help will be greatly appreciated. And please don't link me to anything from http://www.cplusplus.com/ without giving me an example. I'm rather new to C++ and if I was a pro at reading the api at cplusplus.com, I wouldn't be asking this question.
Edit: More info pertaining to my question. No C++11 is not allowed. I am not allowed any 3rd party libraries. So boost is a no go. The machine this has to perform on is a Unix machine.
Final Edit: itwasntpete was the closest to the correct answer, but I can't choose comments. Semaphores is the way I have to go. @Casey true, I'm using a 3rd party library the prof wrote that simplifies concurrency for us. But we're not allowed to use other libraries. It was easier to make that as a rule for people trying to help. Sorry!
I don't think there's any synchronization built in for streams. In C++03 cout is even not necessarily thread-safe. In c++11 it is but still not synchronized.
See this question: Is cout synchronized/thread-safe?
C++11 has support for threads, otherwise you can use OS dependent threading or an easier route might be libraries such as boost which has support for threads, and in a uniform way.
Boost: http://www.boost.org/doc/libs/1_38_0/doc/html/thread.html
Here is some code that should do what you want. You need to link it with boost_thread-mt and pthread, perhaps like gcc -pthread test.cpp -o test -lboost_thread-mt
You'll have to adapt it to use it with your threading library instead of Boost.
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
class Debug {
private:
static boost::mutex mutex;
std::ostream &os;
public:
Debug(std::ostream &os) : os(os)
{
mutex.lock();
}
~Debug()
{
mutex.unlock();
}
template<typename T> friend const Debug& operator<<(const Debug &d, const T& x)
{
d.os << x;
return d;
}
friend const Debug& operator<<(const Debug &d, std::ostream& (*x)(std::ostream&))
{
d.os << x;
return d;
}
};
boost::mutex Debug::mutex;
using namespace std;
using boost::thread;
void f(int i)
{
Debug(cout) << "This is " << i << " a test" << endl;
}
int main()
{
thread t1(f, 1);
thread t2(f, 2);
thread t3(f, 3);
t1.join();
t2.join();
t3.join();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.