In The Go Programming Language, Alan Donovan, page 264 he uses a mutex to read an int.
I don't understand why since an int will fit in a single word, so it cannot be a torn read.
I'm probably wrong, but how? Thanks.
--- Update with code ---
func Balance() int {
mu.Lock()
defer mu.Unlock()
return balance
}
Then down the page
func Withdraw(amount int) bool {
Deposit(-amount)
if Balance() < 0 {
Deposit(amount)
return false // insufficient funds
}
}
This design lets the balance become invalid, which can be observed by a reader, which is then fixed in the book with locking in the Withdraw()
func.
Apologies really, I think I wasted everyone's time :( I set everyone up to fail answering this correctly.
My theory is that if the balance
variable was checked (under lock) that there is sufficient funds before it mutates it, then the locking in the Balance()
func would not be needed, but I still may be wrong, especially as people have mentioned reordering which is kind of mysterious.