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

Share a go language mining pit: closure shared variable problem

藏色散人
Release: 2021-04-12 11:27:49
forward
2579 people have browsed it

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

The results obtained by running are as follows:

closure buggy example...66666normal example...52134normal example 2...52134
Copy after login

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!

Related labels:
source:learnku.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