Go语言学习编程实践:五种模式解决go中的并发问题

简介: Go语言学习编程实践:五种模式解决go中的并发问题

For-Select-Done


我们应该防止程序中发生任何泄露。所以我们应该对于留在程序中的go例程发送信号,让它知道它可以退出。

最常见的就是将for-select循环与通道结合起来,向go程序发送一个关闭信号。我们称它为“完成”通道。

func printIntegers(done <-chan struct{}, intStream <-chan int) {
  for{
     select {
     case i := <-intStream:
     fmt.Println(i)
     case <-done:
     return
     }
   }
}

没有看懂,先记在这里……


扇入模式


1f2a0f51806742fc922ed38b724c8dbd.png

func fanIn(ctx context.Context, fetchers ...<-chan interface{}) <-chan interface{} {
 combinedFetcher := make(chan interface{})
 // 1
 var wg sync.WaitGroup
 wg.Add(len(fetchers))
 // 2
 for _, f := range fetchers {
 f := f
 go func() {
 // 3
 defer wg.Done()
 for{
 select{
 case res := <-f:
 combinedFetcher <- res
 case <-ctx.Done():
 return
 }
 }
 }()
 }
 // 4
 // Channel cleanup
 go func() {
 wg.Wait()
 close(combinedFetcher)
 } ()
 return combinedFetcher
}


从流中获取前 n 个值


7f1f26d541414417a8720827abe02f86.png

func takeFirstN(ctx context.Context, dataSource <-chan interface{}, n int) <-chan interface{} {
 // 1
 takeChannel := make(chan interface{})
 // 2
 go func() {
 defer close(takeChannel)
 // 3 
 for i := 0; i< n; i++ {
 select {
 case val, ok := <-dataSource:
 if !ok{
 return
 }
 takeChannel <- val
 case <-ctx.Done():
 return
 }
 }
 }()
 return takeChannel
}


订阅模式


type Subscription interface {
 Updates() <-chan Item
}
//On the other hand, we are going to use another interface as an abstraction to fetch the data we 
//need:
//另一方面,我们将使用另一个接口作为抽象来获取我们需要的数据。
type Fetcher interface {
 Fetch() (Item, error)
}
//For each of these we are going to have a concrete type implementing them.
//对于其中的每一个,我们都将有一个具体的类型来实现它们。
//For the subscription:
//对于订阅来说。
func NewSubscription(ctx context.Context, fetcher Fetcher, freq int) Subscription {
 s := &sub{
 fetcher: fetcher,
 updates: make(chan Item),
 }
// Running the Task Supposed to fetch our data
 go s.serve(ctx, freq)
 return s
}
type sub struct {
 fetcher Fetcher
 updates chan Item
}
func (s *sub) Updates() <-chan Item {
 return s.updates
}
//We are going to go into more details about what happens inside the serve method.
我们将更详细地介绍服务方法内部发生的事情。
//For the fetcher:
//对于取物者来说。
func NewFetcher(uri string) Fetcher {
 f := &fetcher{
 uri: uri,
 }
 return f
}
type fetcher struct {
 uri string
}
//Inside the serve method
//The serve method consists of a for-select-done type of loop:
//服务方法由一个 for-select-done 类型的循环组成。
func (s *sub) serve(ctx context.Context, checkFrequency int) {
 clock := time.NewTicker(time.Duration(checkFrequency) * time.Second)
 type fetchResult struct {
 fetched Item
 err error
 }
 fetchDone := make(chan fetchResult, 1)
 for {
 select {
 // Clock that triggers the fetch
 case <-clock.C:
 go func() {
fetched, err := s.fetcher.Fetch()
fetchDone <- fetchResult{fetched, err}
 }()
 // Case where the fetch result is
 // Ready to be consumed
 case result := <-fetchDone:
 fetched := result.fetched
 if result.err != nil {
 log.Println("Fetch error: %v \n Waiting the next iteration", result.err.Error())
break
 }
 s.updates <-fetched
 // Case where we need to close the server
 case <-ctx.Done():
 return
 }
 }
}


有一个修正,暂时先不提。


地图模式


func Map(done <-chan struct{}, inputStream <-chan int, operator func(int)int) <-chan int {
 // 1
 mappedStream := make(chan int)
 go func() {
 defer close(mappedStream)
 // 2
 for {
 select {
 case <-done:
 return
 // 3
 case i, ok := <-inputStream:
 if !ok { return }
 //4
 select {
 case <-done:
 return
 case mappedStream <- operator(i):
 }
 }
 }
 }()
 return mappedStream
func main() {
 done := make(chan struct{})
 defer close(done)
 // Generates a channel sending integers
 // From 0 to 9
 range10 := rangeChannel(done, 10)
 multiplierBy10 := func(x int) int {
 return x * 10
 }
 for num := range Map(done, range10, multiplierBy10) {
 fmt.Println(num)
 }
}


过滤模式


1.png

func Filter(done <-chan struct{}, inputStream <-chan int, operator func(int)bool) <-chan int {
 filteredStream := make(chan int)
 go func() {
 defer close(filteredStream)
 for {
 select {
 case <-done:
 return
 case i, ok := <-inputStream:
 if !ok {
 return
 }
 if !operator(i) { break }
 select {
 case <-done:
 return
 case filteredStream <- i:
 }
 }
 }
 }()
 return filteredStream
}
func main() {
 done := make(chan struct{})
 defer close(done)
 // Generates a channel sending integers
 // From 0 to 9
 range10 := rangeChannel(done, 10)
 isEven := func(x int) bool {
 return x % 2 == 0
 }
 for num := range Filter(done, range10, isEven) {
 fmt.Println(num)
 }
}

这五个模式是构建更大、更复杂的 Golang 应用程序的基石。这些解决方案可以解决你在处

理 GO 中的并发问题时可能遇到的问题。此外,你还可以在此基础上修改、扩展和创建新的

模式。

相关文章
|
Linux Go iOS开发
Go语言100个实战案例-进阶与部署篇:使用Go打包生成可执行文件
本文详解Go语言打包与跨平台编译技巧,涵盖`go build`命令、多平台构建、二进制优化及资源嵌入(embed),助你将项目编译为无依赖的独立可执行文件,轻松实现高效分发与部署。
1930 162
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
977 4
|
安全 Java 编译器
对比Java学习Go——基础理论篇
本章介绍了Java开发者学习Go语言的必要性。Go语言以简单、高效、并发为核心设计哲学,摒弃了传统的类继承和异常机制,采用组合、接口和多返回值错误处理,提升了代码清晰度与开发效率。Go直接编译为静态二进制文件,启动迅速、部署简便,其基于Goroutine和Channel的并发模型相较Java的线程与锁机制更轻量安全。此外,Go Modules简化了依赖管理,与Java的Maven/Gradle形成鲜明对比,提升了构建与部署效率。
963 1
|
存储 Java Go
对比Java学习Go——函数、集合和OOP
Go语言的函数支持声明与调用,具备多返回值、命名返回值等特性,结合`func`关键字与类型后置语法,使函数定义简洁直观。函数可作为一等公民传递、赋值或作为参数,支持匿名函数与闭包。Go通过组合与接口实现面向对象编程,结构体定义数据,方法定义行为,接口实现多态,体现了Go语言的简洁与高效设计。
428 4
|
存储 Java 编译器
对比Java学习Go——程序结构与变量
本节对比了Java与Go语言的基础结构,包括“Hello, World!”程序、代码组织方式、入口函数定义、基本数据类型及变量声明方式。Java强调严格的面向对象结构,所有代码需置于类中,入口方法需严格符合`public static void main(String[] args)`格式;而Go语言结构更简洁,使用包和函数组织代码,入口函数为`func main()`。两种语言在变量声明、常量定义、类型系统等方面也存在显著差异,体现了各自的设计哲学。
501 0
|
数据采集 Go API
Go语言实战案例:多协程并发下载网页内容
本文是《Go语言100个实战案例 · 网络与并发篇》第6篇,讲解如何使用 Goroutine 和 Channel 实现多协程并发抓取网页内容,提升网络请求效率。通过实战掌握高并发编程技巧,构建爬虫、内容聚合器等工具,涵盖 WaitGroup、超时控制、错误处理等核心知识点。
|
数据采集 消息中间件 编解码
Go语言实战案例:使用 Goroutine 并发打印
本文通过简单案例讲解 Go 语言核心并发模型 Goroutine,涵盖协程启动、输出控制、主程序退出机制,并结合 sync.WaitGroup 实现并发任务同步,帮助理解 Go 并发设计思想与实际应用。
|
存储 安全 Java
【Golang】(4)Go里面的指针如何?函数与方法怎么不一样?带你了解Go不同于其他高级语言的语法
结构体可以存储一组不同类型的数据,是一种符合类型。Go抛弃了类与继承,同时也抛弃了构造方法,刻意弱化了面向对象的功能,Go并非是一个传统OOP的语言,但是Go依旧有着OOP的影子,通过结构体和方法也可以模拟出一个类。
668 2
|
Cloud Native 安全 Java
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
970 1
|
开发框架 JSON 中间件
Go语言Web开发框架实践:路由、中间件、参数校验
Gin框架以其极简风格、强大路由管理、灵活中间件机制及参数绑定校验系统著称。本文详解其核心功能:1) 路由管理,支持分组与路径参数;2) 中间件机制,实现全局与局部控制;3) 参数绑定,涵盖多种来源;4) 结构体绑定与字段校验,确保数据合法性;5) 自定义校验器扩展功能;6) 统一错误处理提升用户体验。Gin以清晰模块化、流程可控及自动化校验等优势,成为开发者的优选工具。

热门文章

最新文章