Home > Backend Development > Golang > Why Does My Go Concurrency Example Print \'6, 6, 6, 6, 6\' Instead of the Expected Sequence?

Why Does My Go Concurrency Example Print \'6, 6, 6, 6, 6\' Instead of the Expected Sequence?

DDD
Release: 2024-11-29 12:26:11
Original
602 people have browsed it

Why Does My Go Concurrency Example Print

Go Concurrency with for Loop and Anonymous Function: Uncovering the Unexpected

When writing concurrent code in Go, it's important to understand the behavior of anonymous functions. In this example, we explore a scenario where a for loop and an anonymous function produce unexpected output.

The Initial Code

func main() {
    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go func() {
            fmt.Println(i)
            time.Sleep(time.Second * 1)
            wg.Done()
        }()
    }

    wg.Wait()
}
Copy after login

Running this code surprisingly outputs "6, 6, 6, 6, 6" instead of the expected sequence "2, 4, 1, 5, 3." This is because the for loop continues to update the variable i after the goroutines have been launched.

The Closures

The anonymous function in the code above is a closure. Closures capture the variables used in the function's body at the time they're created. In this case, the variable i is captured when the goroutine is launched. However, the loop continues to update i after the goroutine has started.

The Explanation

Since the loop does not terminate until i is greater than 5, i is 6 when the goroutines finally execute. Therefore, each goroutine prints the value of i that was captured in the closure, which is 6 in this case. The expected output is only observed when the variable i is passed as an argument to the anonymous function, effectively creating a copy of the value at the time of the call.

The above is the detailed content of Why Does My Go Concurrency Example Print \'6, 6, 6, 6, 6\' Instead of the Expected Sequence?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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