Boost logo

Boost Users :

Subject: Re: [Boost-users] [format] Thread safety of boost::format
From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2009-06-26 17:06:30


James Madison wrote:
> I was browsing the boost::format docs and did not find anything about
> the Thread safety of boost::format. Essentially I want to craft a
> bunch of error handling methods like this:
>
> void ProcessError(...args...)
> {
> static boost::format formatter(...); //Try to save the cost of
> creating this for every single error
>
> //do stuff
>
> LOG(boost::str(formatter % ...args...);
> }
>
> This method would be called from many, many threads. Is this
> considered safe? Is there some general information about the thread
> safety of boost::format methods somewhere in the docs?
I'm pretty sure the thread safety of Format is the standard mantra of
"one instance from one thread". That is, you can access any given
instance only from one thread unless you synchronize, but multiple
instance in multiple threads do not interfere with each other.

In other words, what you're doing is most definitely not thread-safe.
Think about it this way: every time you use operator %, Format formats
the argument and inserts it into its list of formatted arguments. Unless
this list is thread-local, that cannot possibly be thread-safe, and it
cannot be thread-local for both performance- and correctness reasons.

You can
1) Not make the formatter static.
2) Make a static formatter but simply copy it to a local instance before
modifying it; that might save the cost of parsing.
3) Make the formatter static and completely serialize ProcessError. This
would probably negate any performance gain.

You shouldn't do #2 unless you can actually prove that format
construction takes significant time, of course.

Sebastian


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