Golang并发初探
2016-05-13 本文已影响0人
calvinxiao
演员表
- 马恩 // main goroutine, 每个go程序至少有一个goroutine
- 高老丁1 // 一个去买尿片的goroutine
- 高老丁2 // 一个去买啤酒的goroutine
- 思除 // ch(channel), 用于goroutine之间只能用channel通讯
事情发生经过
- 马恩把思除叫来
- 马恩把思除的微信号告诉高老丁1,然后高老丁1就去买尿片了,回来放好尿片之后就微信一下思除
- 马恩吧思除的微信号告诉高老丁2,然后高老丁2就去买啤酒了,回来放好啤酒之后就微信一下思除(咦,超市不是一般都会吧尿片和啤酒放在一起的么?为什么要两个人去)
- 然后马恩就盯着思除,但是思除的手机一直都不响
- 突然间思除的手机响了
- 突然间思除的手机响了
- 马恩知道尿片和啤酒都买回来了
上面就知最简单的go并发通讯例子。
附上一段并发排序的例子 gist
排序1000万个数字,go library的sort用时3.75秒,把数组分开两边同时用goroutine先排序再合并用时1.98秒
/**
* a sort demo while learning go goroutine
* sorting 10 million numbers concurrently
*/
package main
import (
"fmt"
"sort"
"math/rand"
"time"
)
type IntS []int
// sort.Interface
func (a IntS) Len() int {
return len(a)
}
func (a IntS) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a IntS) Less(i, j int) bool {
return a[i] < a[j]
}
// end sort.Interface
const n = 10000000 // 1e7
func main() {
var a = IntS{}
var b = IntS{}
for i := 0; i < n; i++ {
var t = rand.Intn(n)
a = append(a, t)
b = append(b, t)
}
var start1 = time.Now()
sort.Sort(a)
fmt.Printf("pkg sort took %.6f seconds\n", time.Since(start1).Seconds())
var start2 = time.Now()
superSort(b)
fmt.Printf("sup sort took %.6f seconds\n", time.Since(start2).Seconds())
}
// super sort with goroutine
func superSort(a IntS) IntS {
length := len(a)
if length <= 1 {
return a
}
mid := length / 2
a1 := a[0: mid]
a2 := a[mid: length]
var ch = make(chan int)
go func() {
sort.Sort(a1)
ch <- 1
}()
go func() {
sort.Sort(a2)
ch <- 1
}()
<- ch
<- ch
a3 := make([]int, length)
var i, j, n1, n2 int
n1 = len(a1)
n2 = len(a2)
// merge two sorted list
for ii := 0; ii < length; ii++ {
if (i < n1 && j < n2 && a1[i] < a2[j]) || (i < n1 && j == n2) {
a3[ii] = a1[i]
i++
continue
}
a3[ii] = a2[j]
j++
}
return a3
}
//[calvin:~/source/test/go]$ go run sort.go
//pkg sort took 3.754109 seconds
//sup sort took 1.980207 seconds