Home > Backend Development > Golang > Why does sharing variables in Go lead to different outputs depending on their scope within anonymous functions?

Why does sharing variables in Go lead to different outputs depending on their scope within anonymous functions?

Barbara Streisand
Release: 2024-11-07 02:40:02
Original
669 people have browsed it

Why does sharing variables in Go lead to different outputs depending on their scope within anonymous functions?

Sharing Variables in Go: Understanding the Difference Between Two Cases

In Go, goroutines are lightweight concurrent tasks that can share memory and communicate using channels. Variable sharing among goroutines requires careful handling to avoid data race issues.

Consider the following Go program:

<code class="go">package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
        wg.Add(1)

        x := i

        go func() {
            defer wg.Done()
            fmt.Println(x)
        }()

    }

    wg.Wait()
    fmt.Println("Done")
}</code>
Copy after login

When executed, this program prints the expected output:

4
0
1
3
2
Copy after login

In this case, each goroutine has its own copy of the variable x, which is initialized with the current value of i when the goroutine is created. This is because x is declared within the anonymous function, and its scope is limited to that function.

Now, consider a slight modification to the program:

<code class="go">package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
        wg.Add(1)

        go func() {
            defer wg.Done()
            fmt.Println(i)
        }()

    }

    wg.Wait()
    fmt.Println("Done")
}</code>
Copy after login

This time, the output becomes:

5
5
5
5
5
Copy after login

The explanation lies in the way the variable i is used in the goroutine. Since i is declared outside the anonymous function, it's shared among all goroutines. In this case, when each goroutine executes fmt.Println(i), it's printing the final value of i, which is 5.

To verify this, we can add printing of the memory addresses of x and i within the goroutines. The output shows that x has different addresses for each goroutine, while i has the same address for all goroutines:

0xc0420301e0
0xc0420301f8
0xc0420301e8
0xc0420301f0
0xc042030200
0xc042030208
Copy after login

In conclusion, the difference in variable sharing between the two cases arises from the scope of the variable declared in the anonymous function. When a variable is declared within the anonymous function, it's private to that goroutine. On the other hand, a variable declared outside the anonymous function is shared among all goroutines.

The above is the detailed content of Why does sharing variables in Go lead to different outputs depending on their scope within anonymous functions?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template