golang并发编程实践 -- 简单生产者消费者(with chan)

前端之家收集整理的这篇文章主要介绍了golang并发编程实践 -- 简单生产者消费者(with chan)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文简单介绍如何用golang实现经典的生产者消费者模型。


golang语法简洁,凡可以通过几行代码解决的事情,绝不为了解决该问题而在语言中引入不必要的特性。这个和c++正好相反,c++是个庞大的怪物,我这么形容可能很多c++的fans心里要不舒服了,为了让你在看到诸如子类言论时能够心平气和,建议大家使用一下golang吧。本文不是介绍golang编程语言本身的文章,而是从golang如何让并发编程变得容易的角度来窥视一下golang。下面是用golang提供的chan特性来实现经典的生产者消费者模型的例子:

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. func producer(c chan int) {
  8. for i := 0; i < 10; i++ {
  9. fmt.Printf("Alice puts product,ID is : %d \n",i)
  10. c <- i
  11. }
  12. defer close(c)
  13. }
  14. func consumer(c chan int) {
  15. hasMore := true
  16. var p int
  17. for hasMore {
  18. if p,hasMore = <-c; hasMore {
  19. fmt.Printf("Bob gets product,p)
  20. }
  21. }
  22. }
  23.  
  24. func main() {
  25. c := make(chan int)
  26. go producer(c)
  27. consumer(c)
  28. }

执行结果如下: @H_502_8@Alice puts product, ID is : 0 @H_502_8@Alice puts product, ID is : 1 @H_502_8@Bob gets product, ID is : 0 @H_502_8@Bob gets product, ID is : 1 @H_502_8@Alice puts product, ID is : 2 @H_502_8@Alice puts product, ID is : 3 @H_502_8@Bob gets product, ID is : 2 @H_502_8@Bob gets product, ID is : 3 @H_502_8@Alice puts product, ID is : 4 @H_502_8@Alice puts product, ID is : 5 @H_502_8@Bob gets product, ID is : 4 @H_502_8@Bob gets product, ID is : 5 @H_502_8@Alice puts product, ID is : 6 @H_502_8@Alice puts product, ID is : 7 @H_502_8@Bob gets product, ID is : 6 @H_502_8@Bob gets product, ID is : 7 @H_502_8@Alice puts product, ID is : 8 @H_502_8@Alice puts product, ID is : 9 @H_502_8@Bob gets product, ID is : 8 @H_502_8@Bob gets product, ID is : 9

其中Alice是生产者,Bob是消费者,他们通过chan来达到同步通信的效果。这里并未用到诸如锁之类的概念,而且在golang中go routine本身是非常廉价的。启动一个go routine要比thread占用的资源更少,而且go routine的个数只限制于你机器内存的大小。所以可以根据工程的实际需要启动适宜个数的go routine。

上面代码中有一处要说明的就是如果把consumer函数中的代码修改成:

  1. func consumer(c chan int) {
  2. hasMore := true
  3. // var p int
  4. for hasMore {
  5. if p,hasMore := <-c; hasMore {
  6. fmt.Printf("Bob gets product,p)
  7. }
  8. }
  9. }
再运行之,则程序不会终止。请读者仔细分析下,这个涉及到golang的语法特性,希望以后有机会再blog中介绍下golang的一些有用的特性。

还是简单的对上面的代码做下说明吧,for 中的hashMore和if 表达式中的hasMore变量不是同一个。p,hasMore := <-c 相当于又定义个了个新的变量,其作用域要比for循环中的hasMore作用域要小,希望读者在日后开发golang的时候稍微注意下。

本文是草稿,待日后完善。

猜你在找的Go相关文章