在 Go 语言中管理 Concurrency 的三种方式

相信大家踏入 Go 语言的世界,肯定是被强大的并发(Concurrency)所吸引,Go 语言用最简单的关键字go就可以将任务丢到后台处理,但是开发者怎么有效率的控制并发,这是入门 Go 语言必学的技能,本章会介绍几种方式来带大家认识并发,而这三种方式分别对应到三个不同的名词:WaitGroup,Channel,及 Context。下面用简单的范例带大家了解。

10年的达坂城网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都全网营销的优势是能够根据用户设备显示端的尺寸不同,自动调整达坂城建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联从事“达坂城网站设计”,“达坂城网站推广”以来,每个客户项目都认真落实执行。

WaitGroup

先来了解有什么情境需要使用到 WaitGroup,假设您有两台机器需要同时上传最新的代码,两台机器分别上传完成后,才能执行最后的重启步骤。就像是把一个工作同时拆成好几份同时一起做,可以减少时间,但是最后需要等到全部做完,才能执行下一步,这时候就需要用到 WaitGroup 才能做到。

 
 
 
  1. package main 
  2.  
  3. import ( 
  4.     "fmt" 
  5.     "sync" 
  6. ) 
  7.  
  8. func main() { 
  9.     var wg sync.WaitGroup 
  10.     i := 0 
  11.     wg.Add(3) //task count wait to do 
  12.     go func() { 
  13.         defer wg.Done() // finish task1 
  14.         fmt.Println("goroutine 1 done") 
  15.         i++ 
  16.     }() 
  17.     go func() { 
  18.         defer wg.Done() // finish task2 
  19.         fmt.Println("goroutine 2 done") 
  20.         i++ 
  21.     }() 
  22.     go func() { 
  23.         defer wg.Done() // finish task3 
  24.         fmt.Println("goroutine 3 done") 
  25.         i++ 
  26.     }() 
  27.     wg.Wait() // wait for tasks to be done 
  28.     fmt.Println("all goroutine done") 
  29.     fmt.Println(i) 
  30. } 

Channel

另外一种实际的案例就是,我们需要主动通知一个 Goroutine 进行停止的动作。换句话说,当 App 启动时,会在后台跑一些监控程序,而当整个 App 需要停止前,需要发个 Notification 给后台的监控程序,将其先停止,这时候就需要用到 Channel 来通知。看下下面这个例子:

 
 
 
  1. package main 
  2.  
  3. import ( 
  4.     "fmt" 
  5.     "time" 
  6. ) 
  7.  
  8. func main() { 
  9.     exit := make(chan bool) 
  10.     go func() { 
  11.         for { 
  12.             select { 
  13.             case <-exit: 
  14.                 fmt.Println("Exit") 
  15.                 return 
  16.             case <-time.After(2 * time.Second): 
  17.                 fmt.Println("Monitoring") 
  18.             } 
  19.         } 
  20.     }() 
  21.     time.Sleep(5 * time.Second) 
  22.     fmt.Println("Notify Exit") 
  23.     exit <- true //keep main goroutine alive 
  24.     time.Sleep(5 * time.Second) 
  25. } 

上面的例子可以发现,用了一个 Gogourtine 和 Channel 来控制。可以想像当后台有无数个 Goroutine 的时候,我们就需要用多个 Channel 才能进行控制,也许 Goroutine 内又会产生 Goroutine,开发者这时候就会发现已经无法单纯使用 Channel 来控制多个 Goroutine 了。这时候解决方式会是传递 Context。

Context

大家可以想像,今天有一个后台任务 A,A 任务又产生了 B 任务,B 任务又产生了 C 任务,也就是可以按照此模式一直产生下去,假设中途我们需要停止 A 任务,而 A 又必须告诉 B 及 C 要一起停止,这时候通过 context 方式是最快的了。

 
 
 
  1. package main 
  2.  
  3. import ( 
  4.     "context" 
  5.     "fmt" 
  6.     "time" 
  7. ) 
  8.  
  9. func foo(ctx context.Context, name string) { 
  10.     go bar(ctx, name) // A calls B 
  11.     for { 
  12.         select { 
  13.         case <-ctx.Done(): 
  14.             fmt.Println(name, "A Exit") 
  15.             return 
  16.         case <-time.After(1 * time.Second): 
  17.             fmt.Println(name, "A do something") 
  18.         } 
  19.     } 
  20. } 
  21.  
  22. func bar(ctx context.Context, name string) { 
  23.     for { 
  24.         select { 
  25.         case <-ctx.Done(): 
  26.             fmt.Println(name, "B Exit") 
  27.             return 
  28.         case <-time.After(2 * time.Second): 
  29.             fmt.Println(name, "B do something") 
  30.         } 
  31.     } 
  32. } 
  33.  
  34. func main() { 
  35.     ctx, cancel := context.WithCancel(context.Background()) 
  36.     go foo(ctx, "FooBar") 
  37.     fmt.Println("client release connection, need to notify A, B exit") 
  38.     time.Sleep(5 * time.Second) 
  39.     cancel() //mock client exit, and pass the signal, ctx.Done() gets the signal  time.Sleep(3 * time.Second) 
  40.     time.Sleep(3 * time.Second) 
  41. } 
  42.  
  43. package main 
  44.  
  45. import ( 
  46.     "context" 
  47.     "fmt" 
  48.     "time" 
  49. ) 
  50.  
  51. func foo(ctx context.Context, name string) { 
  52.     go bar(ctx, name) // A calls B 
  53.     for { 
  54.         select { 
  55.         case <-ctx.Done(): 
  56.             fmt.Println(name, "A Exit") 
  57.             return 
  58.         case <-time.After(1 * time.Second): 
  59.             fmt.Println(name, "A do something") 
  60.         } 
  61.     } 
  62. } 
  63.  
  64. func bar(ctx context.Context, name string) { 
  65.     for { 
  66.         select { 
  67.         case <-ctx.Done(): 
  68.             fmt.Println(name, "B Exit") 
  69.             return 
  70.         case <-time.After(2 * time.Second): 
  71.             fmt.Println(name, "B do something") 
  72.         } 
  73.     } 
  74. } 
  75.  
  76. func main() { 
  77.     ctx, cancel := context.WithCancel(context.Background()) 
  78.     go foo(ctx, "FooBar") 
  79.     fmt.Println("client release connection, need to notify A, B exit") 
  80.     time.Sleep(5 * time.Second) 
  81.     cancel() //mock client exit, and pass the signal, ctx.Done() gets the signal  time.Sleep(3 * time.Second) 
  82.     time.Sleep(3 * time.Second) 
  83. } 

大家可以把 context 想成是一个 controller,可以随时控制不确定个数的 Goroutine,由上往下,只要宣告context.WithCancel后,再任意时间点都可以通过cancel()来停止整个后台服务。实际案例会用在当 App 需要重新启动时,要先通知全部 goroutine 停止,正常停止后,才会重新启动 App。

总结

根据不同的情境跟状况来选择不同的方式,做一个总结:

  • WaitGroup:需要将单一个工作分解成多个子任务,等到全部完成后,才能进行下一步,这时候用 WaitGroup 最适合了
  • Channel + Select:Channel 只能用在比较单纯的 Goroutine 情况下,如果要管理多个 Goroutine,建议还是 走 context 会比较适合
  • Context:如果您想一次控制全部的 Goroutine,相信用 context 会是最适合不过的。

当前题目:在 Go 语言中管理 Concurrency 的三种方式
转载源于:http://wkslyf.com/article/dhdoopd.html