Boost logo

Boost :

From: John Torjo (john_at_[hidden])
Date: 2003-04-14 11:39:29


Hi all,

I have created a library to allow very efficient thread-safe logging to STL
streams.

The code has been tested with VC6, gcc3.2 and compiles with Comeau (I don't
have Comeau, so I just used the online version to compile it).
I also provided an example, test, documentation (the doc. is not complete, I
am still working on it, but should give you a feel of how to use the
library).

You can apply this library to allow thread-safe access to ***any*** of your
std::basic_ostream<> derived class.

Here's how you can make access to std::cout thread-safe:

boost::thread_safe_log safe_cout()

    static boost::internal_thread_safe_log_ownthread log( std::cout);
    return log;
}

// code
// write 1000 messages in a thread-safe way
int nThreadID = /* */;
for( int idx = 0; idx < 1000; ++idx)
  safe_cout().ts() << "message " << idx << " from thread " << nThreadID <<
std::endl;

The main idea is the following:
- I have an underlying stream U, to which I want thread-safe access
- I have a safe_cout()-like function that returns a temporary S, that has a
reference to U
- everything you write to S gets buffered (into S's buffer)
- when S is flush()ed, it writes the contents of the buffer to U (this needs
thread-safe access), and then clears S's buffer
- when the buffer is written to U (in a thread-safe manner), what happens is
this: the message is appended to a queue (very fast).
- we have a dedicated thread that reads from that queue, and writes to U.

Please take a look at (I have posted it to
http://www.torjo.com/thread_safe_log/thread_safe_log.zip). Note that I tried
to post it to http://www.yahoogroups.com/files/boost/, but I do not have
rights). I look forward to your comments.

You can also contact me directly at john_at_[hidden]

Best,
John

--
John Torjo
-- "Practical C++" column writer for builder.com.com
Freelancer, C++ consultant
mailto:john_at_[hidden]

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk