开发者

boost::thread and memory model

开发者 https://www.devze.com 2023-03-20 19:46 出处:网络
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 st

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号