Home > Backend Development > Golang > How to capture local variables using closures in Goroutine?

How to capture local variables using closures in Goroutine?

WBOY
Release: 2024-06-05 19:40:01
Original
500 people have browsed it

In Goroutine, closures can be used to capture local variables so that they remain available during Goroutine execution. By passing a local variable as an argument to an anonymous function, you can capture the variable when the goroutine starts. By using closures, data can be shared and modified between concurrently executing Goroutines while ensuring thread safety.

如何在 Goroutine 中使用闭包捕获局部变量?

How to use closures to capture local variables in Goroutine

A closure is a function that can be accessed at the time of its creation An external variable or resource that already exists. In Go, closures are created using anonymous functions.

Capture local variables

When we start an anonymous function in Goroutine, the function can capture all local variables that exist when Goroutine starts.

The following is a code example of how to capture local variables:

package main

import (
    "fmt"
    "time"
)

func main() {
    i := 0

    for i < 10 {
        go func(i int) {
            fmt.Println(i)
        }(i)
        i++
    }

    time.Sleep(time.Second)
}
Copy after login

Practical case

We can use closures to create a counter that executes in parallel. Each Goroutine has its own private counter, which can be safely accessed and modified concurrently:

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
    "time"
)

func main() {
    var wg sync.WaitGroup
    var counter uint64

    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            for j := 0; j < 1000000; j++ {
                // 使用原子操作确保并发安全
                atomic.AddUint64(&counter, 1)
            }
            fmt.Println("Goroutine", i, "finished")
        }(i)
    }

    wg.Wait()
    fmt.Println("Total count:", counter)
}
Copy after login

In this way, we created 10 Goroutines in parallel, each Goroutine has its own counter, and executes 1 million times of self-execution concurrently. Increment operation, and finally we get the total count. Because each Goroutine captures its own local counter variable using a closure, concurrent access and modification of the counter is thread-safe.

The above is the detailed content of How to capture local variables using closures in Goroutine?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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