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 中的并发问题时可能遇到的问题。此外,你还可以在此基础上修改、扩展和创建新的

模式。

目录
打赏
0
0
0
0
172
分享
相关文章
揭秘 Go 语言中空结构体的强大用法
Go 语言中的空结构体 `struct{}` 不包含任何字段,不占用内存空间。它在实际编程中有多种典型用法:1) 结合 map 实现集合(set)类型;2) 与 channel 搭配用于信号通知;3) 申请超大容量的 Slice 和 Array 以节省内存;4) 作为接口实现时明确表示不关注值。此外,需要注意的是,空结构体作为字段时可能会因内存对齐原因占用额外空间。建议将空结构体放在外层结构体的第一个字段以优化内存使用。
监控局域网其他电脑:Go 语言迪杰斯特拉算法的高效应用
在信息化时代,监控局域网成为网络管理与安全防护的关键需求。本文探讨了迪杰斯特拉(Dijkstra)算法在监控局域网中的应用,通过计算最短路径优化数据传输和故障检测。文中提供了使用Go语言实现的代码例程,展示了如何高效地进行网络监控,确保局域网的稳定运行和数据安全。迪杰斯特拉算法能减少传输延迟和带宽消耗,及时发现并处理网络故障,适用于复杂网络环境下的管理和维护。
Go语言Web开发框架实践:路由、中间件、参数校验
Gin框架以其极简风格、强大路由管理、灵活中间件机制及参数绑定校验系统著称。本文详解其核心功能:1) 路由管理,支持分组与路径参数;2) 中间件机制,实现全局与局部控制;3) 参数绑定,涵盖多种来源;4) 结构体绑定与字段校验,确保数据合法性;5) 自定义校验器扩展功能;6) 统一错误处理提升用户体验。Gin以清晰模块化、流程可控及自动化校验等优势,成为开发者的优选工具。
Go语言网络编程:使用 net/http 构建 RESTful API
本章介绍如何使用 Go 语言的 `net/http` 标准库构建 RESTful API。内容涵盖 RESTful API 的基本概念及规范,包括 GET、POST、PUT 和 DELETE 方法的实现。通过定义用户数据结构和模拟数据库,逐步实现获取用户列表、创建用户、更新用户、删除用户的 HTTP 路由处理函数。同时提供辅助函数用于路径参数解析,并展示如何设置路由器启动服务。最后通过 curl 或 Postman 测试接口功能。章节总结了路由分发、JSON 编解码、方法区分、并发安全管理和路径参数解析等关键点,为更复杂需求推荐第三方框架如 Gin、Echo 和 Chi。
Go语言Web开发框架实践:使用 Gin 快速构建 Web 服务
Gin 是一个高效、轻量级的 Go 语言 Web 框架,支持中间件机制,非常适合开发 RESTful API。本文从安装到进阶技巧全面解析 Gin 的使用:快速入门示例(Hello Gin)、定义 RESTful 用户服务(增删改查接口实现),以及推荐实践如参数校验、中间件和路由分组等。通过对比标准库 `net/http`,Gin 提供更简洁灵活的开发体验。此外,还推荐了 GORM、Viper、Zap 等配合使用的工具库,助力高效开发。
Go如何进行高质量编程与性能调优实践
本文介绍了Go语言高质量编程与性能调优的实践方法。高质量编程包括良好的编码习惯(如清晰注释、命名规范)、代码风格与设计(如MVC模式)、简洁明了的代码原则,以及单元测试与代码重构的重要性。性能调优方面,涵盖算法优化、数据结构选择、I/O优化、内存管理、并行与并发处理优化及代码层面的改进。通过这些方法,可有效提升代码质量和系统性能。
60 13
初探Go语言RPC编程手法
总的来说,Go语言的RPC编程是一种强大的工具,让分布式计算变得简单如同本地计算。如果你还没有试过,不妨挑战一下这个新的编程领域,你可能会发现新的世界。
57 10
Go 语言中的 Sync.Map 详解:并发安全的 Map 实现
`sync.Map` 是 Go 语言中用于并发安全操作的 Map 实现,适用于读多写少的场景。它通过两个底层 Map(`read` 和 `dirty`)实现读写分离,提供高效的读性能。主要方法包括 `Store`、`Load`、`Delete` 等。在大量写入时性能可能下降,需谨慎选择使用场景。
《Go语言入门》如何在Windows下安装Go语言编程环境
概述 本文为Go语言学习入门第一篇,《Go语言入门》如何在Windows下安装Go语言编程环境 。 主要讲Go语言编译环境的安装以及基于Notepad++(Go语言插件、语法高亮)的开发环境配置。
1323 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问