Hello, I'm Ganesh. I'm working on FreeDevTools online, currently building a single platform for all development tools, cheat codes, and TL; DRs — a free, open-source hub where developers can quickly find and use tools without the hassle of searching the internet.
In Previous Part, we learned how to detect race conditions. Now let's learn how to fix race conditions.
Fixing Race Conditions
Go provides tools like sync.Mutex to fix race conditions.
You can check with this implementation Link: concurrency
This concept is called mutual exclusion where only one goroutine can access the shared data at a time which will be locked and unlocked after the operation is completed.
That means if one goroutine need to access the shared data they need to first lock the data and then perform the read operation, after they can do operation with the data, and once it is done, the write operation is completed, then they will unlock the shared data.
package main
import (
"fmt"
"sync"
"time"
)
func increment(counter *int, mu *sync.Mutex) {
mu.Lock() // Lock before changing counter
for i := 0; i < 10; i++ {
*counter++
}
mu.Unlock() // Unlock after
}
func main() {
counter := 0
var mu sync.Mutex
for i := 0; i < 5; i++ {
go increment(&counter, &mu)
}
time.Sleep(time.Second)
fmt.Println("Counter:", counter)
}
Output:
Counter: 50
As, there is lock and unlock, it will ensure only one goroutine updates counter at a time.
Currently we just solved the simple race condition, but in real application, there will be very complex race conditions.
To find these and solve will be very complex.
So, I suggest you to just use go race detector to find race conditions.
Conclusion
Similar to dining philosophers problem where philosophers are fighting over shared forks (data).
So, We learned why go routines are not thread safe, how they act under cercumstances, how they can be detected and how to fix it.
In next series, I will explain concepts of go and how to use it to build concurrent programs.
I’ve been building for FreeDevTools.
A collection of UI/UX-focused tools crafted to simplify workflows, save time, and reduce friction when searching for tools and materials.
Any feedback or contributions are welcome!
It’s online, open-source, and ready for anyone to use.
👉 Check it out: FreeDevTools
⭐ Star it on GitHub: freedevtools

Top comments (0)