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

Is this a race condition in Go?

王林
Release: 2024-02-15 09:06:08
forward
578 people have browsed it

这是 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)
    }
}
Copy after login

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)
        }
    }
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template