#Golang并发 Golang原生支持并发。并发的最小单位是goroutine,相互之间的通信采用channel. 这里不涉及锁等复杂的内容,先简单的弄个例子了解一下Golang并发实现的简洁。 #例子,实现slice的求和 具体步骤:创建两个goroutine 一个对slice的前一半数据求和,一个对slice后一半数据求和,最后综合两个结果 完整的代码见: https://github.com/panyingyun/gostudy/blob/master/exp10.go 这里给出片段
runtime.GOMAXPROCS(4) s := make([]int64,100000000) for index,_ := range s { s[index] = int64(index * 2) } c1 := make(chan int64) c2 := make(chan int64) go sum(s[:len(s)/2],c1,"Google") go sum(s[len(s)/2:],c2,"Apple") sum1 := <-c1 fmt.Println(sum1) sum2 := <-c2 fmt.Println(sum2) fmt.Println(sum1 + sum2)@H_301_3@func sum(a []int64,c chan int64,flag string) { //fmt.Println("a = ",a) fmt.Println("time = ",time.Now(),flag) var sum int64 = 0 //sum := 0 for _,v := range a { sum += v } fmt.Println("sum = ",sum,flag) fmt.Println("time = ",flag) c <- sum // send sum to c }@H_301_3@#结果输出 runtime.GOMAXPROCS(1) 时结果:
Gorountine number = 2 Gorountine number = 4 time = 2014-08-13 18:19:22.8741904 +0800 CST Google time = 2014-08-13 18:19:23.0051979 +0800 CST Apple sum = 2499999950000000 Google time = 2014-08-13 18:19:23.1372054 +0800 CST Google sum = 7499999950000000 Apple time = 2014-08-13 18:19:23.1372054 +0800 CST Apple 2499999950000000 7499999950000000 9999999900000000 total exec time = 498.0285ms@H_301_3@runtime.GOMAXPROCS(4) 时结果:
Gorountine number = 2 Gorountine number = 4 time = 2014-08-13 18:18:42.218865 +0800 CST Google time = 2014-08-13 18:18:42.218865 +0800 CST Apple sum = 2499999950000000 Google time = 2014-08-13 18:18:42.3548728 +0800 CST Google 2499999950000000 sum = 7499999950000000 Apple time = 2014-08-13 18:18:42.3568729 +0800 CST Apple 7499999950000000 9999999900000000 total exec time = 378.0216ms@H_301_3@从输出的flag("Google"和"Apple")看,无论cpu设置为1 or 4,在当前这个例子中,两个goroutine宏观上看是并发的, 因为flag交叉打印输出了。另外,runtime.GOMAXPROCS(1) 设置运行cpu为1和4时,整个程序执行的时间略有差异,cpu=4时时间略省,当然这里不能说明cpu数量和性能的关系,毕竟例子太过简单了。
#更多关于并发的例子 (1) 建立两个独立的输出自增数据的通道,主groutine从通道中取数 该例子演示 groutine和channel的使用,一个无缓冲的channel的发送和接受 具体代码:https://github.com/panyingyun/gostudy/blob/master/exp11.go (2)select语句使用的例子 该例子演示了 select 的简单使用 具体代码:https://github.com/panyingyun/gostudy/blob/master/exp12.go (3)chan的range和close操作 该代码演示了range和close操作,实现菲布拉数的输出 具体代码:https://github.com/panyingyun/gostudy/blob/master/exp13.go
#参考文献
原文链接:https://www.f2er.com/go/190829.html
- 关于《goroutine 与调度器》非常形象的介绍底层goroutine的运行机理 http://blog.go-china.org/11-golang-schedule
- RobPike在Google IO 2012大会 上 关于并发的介绍(DOC链接和视频链接) (1)https://talks.golang.org/2012/concurrency.slide#1 (2)https://www.youtube.com/watch?v=f6kdp27TYZs
- Go语言信道和goroutine的一些设计模式的简单例子 http://hit9.org/post/2013-11-18-14-57.html https://github.com/hit9/Go-patterns-with-channel
- Golang高并发的可能案例 http://www.cnblogs.com/ghj1976/p/3762084.html
- Golang goroutine实现的论文分析 http://www.cs.columbia.edu/~aho/cs6998/reports/12-12-11_DeshpandeSponslerWeiss_GO.pdf