Boost logo

Boost Users :

Subject: [Boost-users] [thread] thread specific variable instead of thread specific pointer?
From: Frédéric Bron (frederic.bron_at_[hidden])
Date: 2009-07-12 16:06:42


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_ptr<std::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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net