#2.7 并发 有人把Go比作21世纪的C语言,第一是因为Go语言设计简单,第二,21世纪最重要的就是并行程序设计,而GO语言层面就支持了并行。 ##Goroutines Goroutines是Go并行设计的核心。Goroutines说到底其实就是线程,但是他比线程更小,十几个Goroutines可能体现在底层就是五六个线程,Go语言内部帮你实现了这些Goroutines之间的内存共享。Go语言的作者经常说着这样一句话,不要通过共享来通信,而要通过通信来共享。 Goroutines是通过Go的runtime管理的一个线程管理器。Goroutines通过`go`关键字实现了,其实就是一个普通的函数。 go hello(a, b, c) 通过关键字go就启动了一个Goroutines。我们来看一个例子 package main import ( "fmt" "runtime" ) func say(s string) { for i := 0; i < 5; i++ { runtime.Gosched() fmt.Println(s) } } func main() { go say("world") //开一个新的Goroutines执行 say("hello") //当前Goroutines执行 } 输出: hello world hello world hello world hello world hello 我们可以看到go关键字很方便的就实现了并发编程。 ##channels Goroutines运行在相同的地址空间,因此访问共享内存必须做好同步。那么Goroutines之间如何进行数据的通信呢,Go提供了一个很好的通信机制channel。channel可以与Unix shell 中的双向管道做类比:可以通过它发送或者接收值。这些值只能是特定的类型:channel类型。定义一个channel 时,也需要定义发送到channel 的值的类型。注意,必须使用make 创建channel: ci := make(chan int) cs := make(chan string) cf := make(chan interface{}) channel通过操作符`<-`来接收和发送数据 ch <- v // 发送v到channel ch. v := <-ch // 从ch中接收数据,并赋值给v 我们把这些应用到我们的例子中来: package main import "fmt" func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum // send sum to c } func main() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from c fmt.Println(x, y, x + y) } 默认情况下,channel接收和发送数据都是阻塞的除非另一端已经准备好,这样就使得Goroutines同步变的更加的简单,而不需要显示的lock。所谓阻塞,也就是如果读取(value := <-ch)它将会被阻塞,直到有数据接收。其次,任何发送(ch<-5)将会被阻塞,直到数据被读出。无缓冲channel 是在多个goroutine之间同步很棒的工具。 ##Buffered Channels 上面我们介绍了默认的非缓存类型的channel,不过Go也允许指定channel的缓冲大小,很简单,就是channel可以存储多少元素。ch:= make(chan bool, 4),创建了可以存储4个元素的bool 型channel。在这个channel 中,前4个元素可以无阻塞的写入。当写入第5个元素时,代码将会阻塞,直到其他goroutine从channel 中读取一些元素,腾出空间。 ch := make(chan type, value) value == 0 ! 无缓冲(阻塞) value > 0 ! 缓冲(非阻塞,直到value 个元素) 我们看一下下面这个例子,你可以在自己本机测试一下,修改相应的value值 package main import "fmt" func main() { c := make(chan int, 2)//修改2为1就报错,修改2为3可以正常运行 c <- 1 c <- 2 fmt.Println(<-c) fmt.Println(<-c) } ##Range和Close ##Select ## links * [目录]() * 上一章: [interface](<2.6.md>) * 下一节: [总结](<2.8.md>) ## LastModified * $Id$