Home >Backend Development >Golang >Why Does My Go Concurrency Example Print \'6\' Five Times Instead of Unique Numbers?

Why Does My Go Concurrency Example Print \'6\' Five Times Instead of Unique Numbers?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 03:07:11482browse

Why Does My Go Concurrency Example Print

Go Concurrency with for Loop and Anonymous Function Excitation

In a pursuit to improve concurrency comprehension using Go's sync.WaitGroup, a developer encountered an unexpected behavior with code designed to facilitate multiple uploads to Amazon S3. The initial code snippets are presented:

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()
}

To the developer's surprise, the output consistently displayed "6, 6, 6, 6, 6," deviating from the anticipated order such as "2, 4, 1, 5, 3." As the loop iterates up to 5, the unexpected result of 6 appeared. Subsequent modifications that incorporated i as an argument within the anonymous function yielded the intended output.

Unveiling the Rationale

The documentation for closures in Go sheds light on this behavior. As the for loop progresses, the closures captured i's value at the time of its definition. Therefore, even though the loop terminates after i reaches 5, the goroutines execute with a shared value of 6, ultimately printing "6, 6, 6, 6, 6."

By passing i as an argument, a new variable captures the value of i at the moment of its declaration, resulting in the desired output.

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

Statement:
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