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
}
Yes you do.
Imagine the situation where two threads are trying to add 1 to someValue
. A thread does this by:
someValue
into a registersomeValue
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.
someValue
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With