Do I need to protect this variable with a lock?

后端 未结 6 1259
天涯浪人
天涯浪人 2021-02-15 11:58

so I have a boolean type in C++ on a multiprocessor machine. The variable starts out life as true, and then there are a few threads, any one or more of which might write it to b

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-15 12:49

    You are asking about two things.

    First you are asking about atomicity of bool assignment. No there is no guarantee that boolean assignment will be atomic operation. In practice it usually is, but you shouldn't rely on this. Some strange architecture may implement bool assignment in many machine instructions...

    Secondary you are asking about corruption of data due to parallel writes - in practice transport from CPU to memory is done by a bus, which almost always contains more bits than primitive types you are working on. So such corruption may happen for very strange architecture or when working on big numbers (not supported by the system natively). In practice you will usually get 3 or 7. But again, you can't rely on it.

    To conclude this - you need a lock.

提交回复
热议问题