Pessimitic Locking in GO
Running the following code on threads will give you inconsistent results.
func incCount(){
count++;
wg.Done()
}
func doCount(){
for i:=0; i < 1000000; i++{
wg.Add(1)
go incCount()
}
}
Reason:
Count++ (increment operation) is not atomic in nature. Micro-operations in registers
- movl %rdi, %tmp LOAD
- addl $1, %tmp ADD
- movl %tmp, %rdi STORE
Solution:
Lock and Unlock the operation (count++) using Mutex, so that only one thread runs the operation at a time.
var mu sync.Mutex
mu.Lock()
count++;
mu.Unlock()
Reference:
Pessimitic Locking with Mutex