[log] how to set attributes under multi-threaded application

In boost::log documentation, there's some code as following: * typedef attrs::mutable_constant< int > int_constant_t; boost::shared_ptr< int_constant_t > attr(new int_constant_t(-5)); lg.add_attribute("MyInteger", attr); BOOST_LOG(lg) << "This record has MyInteger == -5"; **// Change the attribute value attr->set_value(100); BOOST_LOG(lg) << "This record has MyInteger == 100"; * Now I have a situation in my multi-threading app: the 'attr->set_value()' could be called in different threads, so the following 'BOOST_LOG(lg)...' could access wrong attributes that is set by another thread. If I use a mutex to protect this, it would be stupid, because the log line might be filtered out, that means the 'locking mutex' is not neccessary. Who can help ? Jinqiang *btw, the boost::log documentation isn't too good, when I read it, I felt I lost in a juggle.*

On 08/03/2011 08:29 AM, Jinqiang Zhang wrote:
In boost::log documentation, there's some code as following:
* typedef attrs::mutable_constant< int> int_constant_t; boost::shared_ptr< int_constant_t> attr(new int_constant_t(-5)); lg.add_attribute("MyInteger", attr); BOOST_LOG(lg)<< "This record has MyInteger == -5";
**// Change the attribute value attr->set_value(100); BOOST_LOG(lg)<< "This record has MyInteger == 100"; * Now I have a situation in my multi-threading app: the 'attr->set_value()' could be called in different threads, so the following 'BOOST_LOG(lg)...' could access wrong attributes that is set by another thread. If I use a mutex to protect this, it would be stupid, because the log line might be filtered out, that means the 'locking mutex' is not neccessary.
If thread synchronizaion is what bothers you, mutable constant has internal locking ability, you can specify mutex and lock types in the mutable_constant template parameters. You can find an example in the docs: <http://boost-log.sourceforge.net/libs/log/doc/html/log/detailed/attributes.html#log.detailed.attributes.mutable_constant> So, when internal locking is used, you don't have to externally synchronize access to this attribute, neither when you update its value nor when you write log records involving it. On the other hand, if you simply try to tag a specific log record with an attribute (e.g. you want to make sure that a particular record has MyInteger value -5 attached) then thread-specific attributes would be a better option. You can add a scoped thread-specific attribute for this record, this will not affect log records generated by other threads and will not require any synchronization either. You can read more about scoped attributes here: <http://boost-log.sourceforge.net/libs/log/doc/html/log/detailed/utilities.html#log.detailed.utilities.scoped_attributes>
participants (2)
-
Andrey Semashev
-
Jinqiang Zhang