Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
You may have noticed in previous examples that the output is
sometimes garbled. C++ iostreams were not created with threading in mind, so
there s nothing to keep one thread s output from interfering with another
thread s output. Thus, you must write your applications so that they
synchronize the use of iostreams.
To solve the problem, we need to create the entire output
packet first and then explicitly decide when to try to send it to the console.
One simple solution is to write the information to an ostringstream and
then use a single object with a mutex as the point of output among all threads,
to prevent more than one thread from writing at the same time:
//: C11:Display.h
// Prevents ostream collisions.
#ifndef DISPLAY_H
#define DISPLAY_H
#include <iostream>
#include <sstream>
#include "zthread/Mutex.h"
#include "zthread/Guard.h"
class Display { // Share one of these among all threads
ZThread::Mutex iolock;
public:
void output(std::ostringstream& os) {
ZThread::Guard<ZThread::Mutex> g(iolock);
std::cout << os.str();
}
};
#endif // DISPLAY_H ///:~
This way, the standard operator<<( )
functions are predefined for us and the object can be built in memory using
familiar ostream operators. When a task wants to display output, it
creates a temporary ostringstream object that it uses to build up the
desired output message. When it calls output( ), the mutex prevents
multiple threads from writing to this Display object. (You must use only
one Display object in your program, as you ll see in the following
examples.)
This just shows the basic idea, but if necessary, you can
build a more elaborate framework. For example, you could enforce the
requirement that there be only one Display object in a program by making
it a Singleton. (The ZThread library has a Singleton template to support
Singletons.)
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |