Do I need to protect this variable with a lock?

后端 未结 6 1229
天涯浪人
天涯浪人 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:52

    On most commodity hardware a single word reads/writes are atomic, so no, two (or more) competing writes (and reads) to the same memory location are not going to corrupt the value. What is important here is cache coherence between CPUs.

    Again, on commodity hardware you might get away with just marking that single boolean variable volatile (which has been declared useless for concurrent programming btw) to prevent compiler from optimizing it out into a register, but only if you really don't care about the order of writes.

    Let me re-iterate this with a check-list:

    • Are you ready do lose some updates to that boolean?
    • Are you sure no other memory updates that come before the boolean flip in the source code but might get reordered after that flip are going to mess things up?
    • Are you sure you don't care about order of events in your application?

    If you have three strong "yes" answers, you might get away with not protecting that flag. Still consider inserting acquire memory barrier before reading the variable, and release memory barrier before writing it. My suggestion though would be to re-think the design, and lay out clear synchronous inter-thread communications and event sequencing.

    Hope this helps.

提交回复
热议问题