Two coroutines write the same term of the slice in parallel. May panic errors occur?

Viewed 28

Two coroutines write the same term of the slice in parallel. May panic errors occur?

I not found document about this.

Concurrent reads and writes only cause data disorder, not happen panic error?

import (
    "fmt"
    "strconv"
    "time"
)

func main() {
    arr := []string{"a", "b", "c", "d"}

    // write 1
    go func() {
        for {
            arr[2] = strconv.FormatInt(time.Now().Unix(), 10)
        }
    }()

    // read 1
    go func() {
        for {
            fmt.Println(arr[2])
        }
    }()

    // write 2
    go func() {
        for {
            arr[2] = strconv.FormatInt(time.Now().Unix(), 10)
        }
    }()

    time.Sleep(10 * time.Second)
    return
}
1 Answers

This is a data race. Try running your code using the -race flag. e.g. go run -race main.go.

Also, here's a nice doc on Data Race Detector

Related