Just an hour ago, I was asked to create a race condition and solve it with a mutex.
I wrote the following code to depict a race condition :
func main() {
var data int
go func() {
data++
}()
if data == 0 {
fmt.Println("The value of data is", data)
} else {
fmt.Println("The value of data is", data)
}
}
And then I added the mutex to solve the race condition, as follows:
func main() {
var data int
var mu sync.Mutex
go func() {
mu.Lock()
data++
mu.Unlock()
}()
mu.Lock()
if data == 0 {
fmt.Println("The value of data is", data)
} else {
fmt.Println("The value of data is", data)
}
mu.Unlock()
}
The interviewer commented that the first code doesn’t depict a Race condition, correct me if I am wrong, but I think it does, can you help?
I think Go is flagged the code as Race condition because you are accesing a global var from a goroutine. A race condition occurs when two threads access a shared variable at the same time -
If yu run your program without the race flag, it runs without problem. (the gourutine does not get chance to be executed)
for you have a race condition, so, the data race you need to have 2 or more goroutines access the same variable concurrently and at least one of the accesses is a write operation, like this:
package main
var balance int
func Deposit(amount int) {
balance = balance + amount
}
func Balance() int {
return balance
}
func main() {
go Deposit(200)
go Deposit(100)
}
to solve the problem
package bank
import "sync"
var (
mu sync.Mutex
balance int
)
func Deposit(amount int) {
mu.Lock()
balance = balance + amount
mu.Unlock()
}
func Balance() int {
mu.Lock()
defer mu.Unlock()
return balance
}
Actually, this is what @MukulLatiyan’s code does. There are two threads of execution (the spawned-off goroutine and the main code thread, that can be considered a goroutine in this context), and one of them does a write operation.
Yes, this is true, I wanted to demonstrate another clearer example of this with more than one goroutine without being the main, and I also ran his code with -race and was accused of data race