Mutual exclusion lock in golang with examples | Synchronized data access
A mutex is used to ensure exclusive access to data. The standard library offers mutex locking( mutual exclusion lock) using sync.Mutex. In this post I would like to share what I've learned about mutex locking and examples that I've used in my personal experiment
What is mutual exclusion (mutex)
A mutual exclusion (mutex) is a program object that prevents simultaneous access to a shared resource.
Mutual exclusion is a property of concurrency control which states that " NO TWO PROCESS SHOULD ACCESS THE SAME RESOURCE AT THE SAME TIME ".
Mutex object is introduced to let you access data in a synchronize fashion to prevent race conditions.
In my examples, I wanted to access and update a counter variable with multiple go routine.
Chaotic Data access without mutex locking
See without_lock.go, where I didn't use any locking and if you run this you might see some output something like below:
Value after Worker 2 is done: 1 Value after Worker 19 is done: 5 Value after Worker 1 is done: 3 Value after Worker 12 is done: 13 Value after Worker 11 is done: 6 Value after Worker 5 is done: 8 Value after Worker 6 is done: 9 Value after Worker 20 is done: 32 ....
Note: Only the last number is important here. By 1,5,3,13,6,8,9,32 you can see that the increment didn't happened in sequence.
Meaning, multiple go routine is accessing and updating the same value at the same time thus this random output
Bringing Order with mutex lock
Now if you run main.go which have mutex locking in between you can see the counter is incremented in sequence like this.
Value after Worker 0 is done: 1 Value after Worker 48 is done: 2 Value after Worker 62 is done: 3 Value after Worker 80 is done: 4 Value after Worker 77 is done: 5 Value after Worker 95 is done: 6
Meaning no other go-routine can access the the counter variable while being access by other go routine.
So finally we synchronized data access by mutex locking !