Home  >  Article  >  Backend Development  >  Is this a race condition in Go?

Is this a race condition in Go?

王林
王林forward
2024-02-15 09:06:08508browse

这是 Go 中的竞争条件吗

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!

Question content

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.

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete