Race Condition and Data Race
package main
import "fmt"
func main() {
wait := make(chan struct{})
n := 0
go func() {
n++ // read, increment, write
close(wait)
}()
n++ // conflicting access
<-wait
fmt.Println(n) // Output: <unspecified>
}func main() {
ch := make(chan int)
go func() {
n := 0 // A local variable is only visible to one goroutine.
n++
ch <- n // The data leaves one goroutine...
}()
n := <-ch // ...and arrives safely in another.
n++
fmt.Println(n) // Output: 2
}package main
import "fmt"
func deposit(balance *int, amount int){
*balance += amount //add amount to balance
}
func withdraw(balance *int, amount int){
*balance -= amount //subtract amount from balance
}
func main() {
balance := 100
go deposit(&balance,10) //depositing 10
withdraw(&balance, 50) //withdrawing 50
fmt.Println(balance)
}Last updated