Golang 闭包和协程的使用
    		       		warning:
    		            这篇文章距离上次修改已过434天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "fmt"
    "time"
)
 
// 定义一个函数工厂,它返回一个新的函数,该函数会记录其被调用的次数。
func makeCounter(counterName string) func() int {
    var count int
    return func() int {
        count++
        fmt.Printf("%s: %d\n", counterName, count)
        return count
    }
}
 
func main() {
    // 创建一个计数器
    counter := makeCounter("counter")
 
    // 使用计数器
    counter() // 输出: counter: 1
    counter() // 输出: counter: 2
 
    // 使用Go的goroutine和通道实现异步计数
    var wg sync.WaitGroup
    wg.Add(1)
    done := make(chan bool)
 
    go func() {
        defer wg.Done()
        for i := 0; i < 5; i++ {
            counter() // 输出: counter: 3, ..., counter: 7
            time.Sleep(1 * time.Second)
        }
        done <- true
    }()
 
    // 等待goroutine完成
    wg.Wait()
    <-done
}这段代码首先定义了一个函数工厂makeCounter,它返回一个闭包。闭包中包含一个局部变量count,每次调用返回的函数时,count都会递增,并打印当前的值。然后,我们创建了一个计数器,并调用了两次。接着,我们使用Go的goroutine和通道实现了一个异步的计数过程,在一个单独的goroutine中,我们每秒钟递增计数并打印出来,直到5次。最后,我们使用sync.WaitGroup来等待goroutine完成,并通过通道接收完成信号。这个例子展示了Golang中闭包和协程的基本使用方法。
评论已关闭