Home  >  Article  >  Backend Development  >  Share a go language mining pit: closure shared variable problem

Share a go language mining pit: closure shared variable problem

藏色散人
藏色散人forward
2021-04-12 11:27:362548browse

The tutorial column of golang will share with you a go language pitfall: closure shared variable problem. I hope it will be helpful to friends in need!

Share a go language mining pit: closure shared variable problem

Without further ado, let’s just look at the code and comments:

package mainimport (
    "fmt"
    "time")func main() {
    // 错误示例(打印出的结果是5个6)
    fmt.Println("closure buggy example...")
    for i := 1; i <= 5; i++ {
        // 每个goroutine共享一个变量,goroutine还没开始的时候,i已经变成了6
        go func() {
            fmt.Println(i)
        }()
    }
    time.Sleep(1 * time.Second)


    // 正确示例1:
    fmt.Println("normal example...")
    for i := 1; i <= 5; i++ {
        go func(i int) {   // 使用局部变量
            fmt.Println(i)
        }(i)
    }
    time.Sleep(1 * time.Second)

    // 正确示例2:
    fmt.Println("normal example 2...")
    for i := 1; i <= 5; i++ {
        i := i  // 为每个闭包创建一个变量
        go func() {
            fmt.Println(i)
        }()
    }
    time.Sleep(1 * time.Second)}

The results obtained by running are as follows:

closure buggy example...66666normal example...52134normal example 2...52134

See the code comments for reasons and solutions. The first example is an incorrect example, and the second and third examples are correct examples.

The above is the detailed content of Share a go language mining pit: closure shared variable problem. For more information, please follow other related articles on the PHP Chinese website!

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