Suppose I have a bit of boiler-plate multi-threaded code, e.g. as below. I wondered what guarantees (if any) there are that multiple threads using that code will always see a current version of the state. I know C++ guarantees very little about the memory model, and I think I read somewhere that even declaring state volatile might not help. Yet in practice people happily use boost::thread, and its documentation does not come with a big warning that says mutexes开发者_运维技巧 are not useful unless you only use external state :-) I am assuming there must be some magic that boost does behind the scenes, or should I be calling __sync_synchronize() every time I do anything?
class Blah {
typedef (some horribly complex data structure) State;
State state;
boost::mutex m;
(...)
void use ()
{
boost::lock_guard<boost::mutex> dummy (m);
(do something to state, being especially careful to maintain invariants)
}
};
Mutex lock/unlock implies a memory barrier. (Although I cannot find this stated in the boost::mutex documentation, I guarantee it is stated somewhere in the documentation for every mutex implementation Boost relies upon.)
This code is fine.
精彩评论