How to understand this behavior of goroutine?

后端 未结 2 1568
慢半拍i
慢半拍i 2021-01-15 21:01
package main
import (  
    \"fmt\"
    \"time\"
)
type field struct {  
    name string
}
func (p *field) print() {  
    fmt.Println(p.name)
}
func main() {  
             


        
2条回答
  •  遥遥无期
    2021-01-15 21:37

    As stated above there’s a race condition it’s result depends on delays on different processes and not well defined and predictable. For example if you add time.Sleep(1*time.Seconds) you likely to get a correct result. Because usually goroutine prints faster than 1second and will have correct variable v but it’s a very bad way.

    Golang has a special race detector tool which helps to find such situations. I recommend read about it while reading testing. Definitely it’s worth it.

    There’s another way - explicitly pass variable value at goroutine start:

    for _, v := range data {
         go func(iv field) {
                iv.print()
          }(v)
     }
    

    Here v will be copied to iv (“internal v”) on every iteration and each goroutine will use correct value.

提交回复
热议问题