Do I need to protect this variable with a lock?

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

    If only you're checking the state of the variable and setting it to false in one direction ever, there's not much to worry about except that some of the threads may be a little late to see the variable is already set to false. (this may be overcome to some degree by the use of 'volatile' keyword.) Then two threads may set it to false, which is no problem since the variable is set to a single value in one direction. Let's say boolean write to the memory location is not guaranteed to be atomic, what's the harm? The final value they both will write is the same.

    Still, you would have to use a method of locking if:

    • Value setting is not one-direction only: you set it to false, then back to true, then false again, etc.
    • You take some dependent action on the information which thread had set the value to false. Because there obviously may be two winners.

提交回复
热议问题