Multithreading: do I need protect my variable in read-only method?

前端 未结 5 1197
庸人自扰
庸人自扰 2021-01-12 09:34

I have few questions about using lock to protect my shared data structure. I am using C/C++/ObjC/Objc++

For example I have a counter class that used in multi-thread

5条回答
  •  离开以前
    2021-01-12 10:27

    Yes, unless you can guarantee that changes to the underlying variable counter are atomic, you need the mutex.

    Classic example, say counter is a two-byte value that's incremented in (non-atomic) stages:

    (a) add 1 to lower byte
        if lower byte is 0:
    (b)     add 1 to upper byte
    

    and the initial value is 255.

    If another thread comes in anywhere between the lower byte change a and the upper byte change b, it will read 0 rather than the correct 255 (pre-increment) or 256 (post-increment).

    In terms of what data types are atomic, the latest C++ standard defines them in the header.

    If you don't have C++11 capabilities, then it's down to the implementation what types are atomic.

提交回复
热议问题