[thread] thread specific variable instead of thread specific pointer?

I would like to have a variable specific to each thread. This means I would like to use the same variable name and that this name corresponds to different instances in different threads. For example, I would like to build a log stream that writes in different files in different threads. For example I would like to have a variable "flog" that behaves like a std::ostream: flog << "hello world!" ; I have found the two following solutions based on the use of boost::thread_specific_ptr but I am not fully satisfied with them: boost::thread_specific_ptrstd::ofstream flogs ; // first solution using a function std::ostream &flog() { return *flogs.get() ; } // but I then have to add () after flog: flog() << "hello world!" ; // second solution using a macro #define flog flog() // but macros are not very recommended in C++. Any other idea that would allow me to write flog << "hello world!" like with std::cout? Note that I also tried to write a class derived from ostream with only one instance flog. This class had a special stream buffer using a thread specific pointer. However, the flog instance stores some informations like the precision of real numbers (flog << setprecision(10) for example) and the output of one thread can then interfere with the output of other threads... Regards, Frédéric

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sunday 12 July 2009, Frédéric Bron wrote:
boost::thread_specific_ptrstd::ofstream flogs ;
// first solution using a function std::ostream &flog() { return *flogs.get() ; } // but I then have to add () after flog: flog() << "hello world!" ;
// second solution using a macro #define flog flog() // but macros are not very recommended in C++.
Any other idea that would allow me to write flog << "hello world!" like with std::cout?
Note that I also tried to write a class derived from ostream with only one instance flog. This class had a special stream buffer using a thread specific pointer. However, the flog instance stores some informations like the precision of real numbers (flog << setprecision(10) for example) and the output of one thread can then interfere with the output of other threads...
So put them all in the thread specific pointer. I don't see what's so
objectionable about flog() << "hello world!" though.
struct flogs_impl
{
std::ofstream;
unsigned precision;
//...
};
class flogs
{
//...
boost::thread_specific_ptr
participants (2)
-
Frank Mori Hess
-
Frédéric Bron