2

There is a variable(e.g. int temp;) in the multi-thread environment. Some threads write to it, with write-lock protected. while others read the variable, but without any lock.

My question is: If the variable is writed to be one of element in a SET(e.g. {1, 2, 3}), by some threads repeatedly. Is it always one of that SET, when I read it.

hmjd
  • 120,187
  • 20
  • 207
  • 252
hello.co
  • 746
  • 3
  • 21

3 Answers3

4

The rule is very simple: if two or more threads access the same variable and at least one of those threads writes to it, you must synchronize all of those accesses. If you do not, the behavior is undefined.

volatile won't help here; either use a mutex or a condition variable, or make the variable itself atomic. (And "atomic" means C++11 atomic, not some selection of properties that someone thinks will act pretty well in multi-threaded applications).

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • I agree with you. I put the question here because I have seen many code written, supposing the answer of my question is 'YES', which make me very confused. But it may usually 'YES', :).. – hello.co Mar 27 '13 at 11:33
0

Yes it will if your variable's type is immutable because SET does not allow duplicates

Refer SET

Mohan Raj B
  • 1,015
  • 7
  • 14
0

If noone write value from outside of your SET, the value will remains from this SET. You can possibly need to use volatile in your case.

SpongeBobFan
  • 964
  • 5
  • 13