在 go 中,通过通道可以安全地跨 goroutine 共享函数:创建通道传递函数值。在 goroutine 中启动函数并将其传递到通道。从通道接收函数并使用它。例如,使用通道传递 count 函数值来并行计数列表元素。
在 Go 中跨 Goroutine 共享函数
在 Go 中,goroutine 是轻量级线程,可用于并发编程。有时,您可能希望在多个 goroutine 中使用相同的函数。本文将展示如何实现这一目标,并提供一个实际示例。
方法
立即学习“go语言免费学习笔记(深入)”;
Go 为 goroutine 之间共享数据提供了安全的机制,称为通道。通道是一种 FIFO(先进先出)队列,goroutine 可以从中发送或接收值。
要跨 goroutine 共享函数,可以:
-
创建一个通道来传递函数值:
funcValueChannel := make(chan func())
在 Goroutine 中启动函数并将其传递到通道:
go func() { funcValueChannel <- myFunc }()
在需要时从通道接收函数并使用它:
otherGoroutineFunc := <-funcValueChannel otherGoroutineFunc()
实战案例
假设您有一个 Count 函数,可计算给定列表中的元素数量。您希望在多个 goroutine 中使用此函数来并行计数多个列表。
以下是实现代码:
package main
import "fmt"
import "sync"
import "time"
func main() {
//创建一个协程组来等待所有协程完成
var wg sync.WaitGroup
//定义一个通道来传递 Count 函数值
funcValueChannel := make(chan func([]int) int)
//启动多个协程,每个协程都在一个不同的列表上调用 Count 函数
for i := 0; i < 5; i++ {
// 启动一个协程
wg.Add(1)
go func(i int) {
// 将 Count 函数值发送到通道
funcValueChannel <- func(nums []int) int { return Count(nums) }
defer wg.Done() //任务完成后将协程组计数减 1
}(i)
}
// 创建一个切片,其中包含需要计数的数字列表。
nums := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12},
{13, 14, 15},
}
// 从通道接收函数值并计算列表中的元素数量
for i := 0; i < 5; i++ {
// 从通道接收 Count 函数值
countFunc := <-funcValueChannel
// 计算列表中元素的数量
result := countFunc(nums[i])
fmt.Printf("Goroutine %d: Result: %dn", i+1, result)
}
// 等待所有协程完成,关闭通道
wg.Wait()
close(funcValueChannel)
}
// Count 返回给定列表中元素的数量
func Count(nums []int) int {
time.Sleep(100 * time.Millisecond) // 模拟一些处理时间
count := 0
for _, num := range nums {
count += num
}
return count
}
在这段代码中,我们创建了一个通道 funcValueChannel,用于传递 Count 函数值。然后,我们启动多个 goroutine,每个 goroutine 都将 Count 函数值发送到通道。在主 goroutine 中,我们从通道接收 Count 函数值并使用它来计算列表中的元素数量。
通过使用通道,我们可以在 goroutine 之间安全地共享 Count 函数,从而实现并行计数。