Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to add thread locking to simple variables? [duplicate]

Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}
like image 355
weuhi Avatar asked Jul 04 '17 08:07

weuhi


1 Answers

Yes you do.

Imagine the situation where two threads are trying to add 1 to someValue. A thread does this by:

  1. read someValue into a register
  2. Add 1
  3. write someValue back

If both threads do operation 1 before either does operation 3, you will get a different answer than if one thread does all three operations before the other thread does operation 1.

There are also more subtle issues, in that an optimising compiler might not write the modified value back from the register for some time - if at all. Also, modern CPUs have multiple cores each with its own cache. The CPU writing a value back to memory doesn't guarantee it gets to memory straight away. It may just get as far as the core's cache. You need what's called a memory barrier to ensure that everything gets neatly written back to main memory.

On the larger scale, you'll need locking to ensure consistency between the variables in your class. So, if the state is meant to represent some property of someValue e.g. is it an integer or not, you'll need locking to ensure everybody always has a consistent view i.e.

  1. modify someValue
  2. test the new value
  3. set state accordingly.

The above three operations have to appear to be atomic, or if the object is examined after operation 1 but before operation 3, it will be in an inconsistent state.

like image 95
JeremyP Avatar answered Oct 21 '22 15:10

JeremyP