golang,go,博客,开源,编程

lacet concurrency Bridge示例

Published on with 0 views and 0 comments
import (
	"context"
	"fmt"

	"github.com/duke-git/lancet/v2/concurrency"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	c := concurrency.NewChannel[int]()
	genVals := func() <-chan <-chan int {
		out := make(chan (<-chan int))
		go func() {
			defer close(out)
			for i := 1; i <= 5; i++ {
				stream := make(chan int, 1)
				stream <- i
				close(stream)
				out <- stream
			}
		}()
		return out
	}

	for v := range c.Bridge(ctx, genVals()) {
		fmt.Println(v)
	}
	// Output:
	// 1
	// 2
	// 3
	// 4
	// 5
}

用于将一个通道的通道中的值桥接到一个输出通道中

举例:如果有一个任务,分成n个部分给n个协程处理,处理之后产生未知个结果,要在某个协程中统一对这些结果进行处理,这些结果没有顺序,产生的时间也未知。那么用bridge。


标题:lacet concurrency Bridge示例
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/01/09/1736407398746.html
联系:scotttu@163.com