php editor Apple will answer a common question for you in this article: "Is this a race condition in Go?" When writing concurrent programs, the race condition is A common problem that can lead to data inconsistencies and other unexpected results. In the Go language, we can use mechanisms such as mutex locks and channels to avoid race conditions. Let’s discuss it together!
func main() { m := map[string]int{ "foo": 42, "bar": 1337, } go func() { time.Sleep(1 * time.Second) tmp := map[string]int{ "foo": 44, "bar": 1339, } m = tmp }() for { val := m["foo"] fmt.Println(val) } }
I see this in a lot of packages.
Why isn't this considered a race condition?
go run -race .
No errors.
As @volker pointed out, this is a data race. And since it's only written once, it's difficult to detect. Here is a modified demo that can easily trigger data race errors:
package main import ( "fmt" "time" ) func main() { m := map[string]int{ "foo": 42, "bar": 1337, } done := make(chan any) go func() { for i := 0; i < 100; i++ { time.Sleep(time.Microsecond) tmp := map[string]int{ "foo": 44, "bar": 1339, } m = tmp } close(done) }() for { select { case <-done: return default: val := m["foo"] fmt.Println(val) } } }
The above is the detailed content of Is this a race condition in Go?. For more information, please follow other related articles on the PHP Chinese website!