channel是消息传递的机制,用于多线程环境下lock free synchronization.
它同时具备2个特性:
1. 消息传递
2. 同步
golang里的channel的性能,可以参考前一篇:http://blog.sina.com.cn/s/blog_630c58cb01016xur.html
go test -v -test.bench=".*" runtime
在我的pc上的结果是:
BenchmarkChanUncontended
50000000
67.3 ns/op
BenchmarkChanContended
50000000
67.7 ns/op
BenchmarkChanSync
10000000
181 ns/op
BenchmarkChanProdCons0
10000000
198 ns/op
BenchmarkChanProdCons10
20000000
98.2 ns/op
BenchmarkChanProdCons100
50000000
73.4 ns/op
BenchmarkChanProdConsWor
k0
1000000
1874 ns/op
BenchmarkChanProdConsWor
k10
1000000
1805 ns/op
BenchmarkChanProdConsWor
k100
1000000
1771 ns/op
BenchmarkChanCreation
10000000
195 ns/op
BenchmarkChanSem
50000000
66.3 ns/op
channel的实现,都在$GOROOT/src/pkg/runtime/chan.c里
它是通过共享内存实现的
struct Hchan {
}
ch := make(chan interface{},5)
具体的实现是chan.c里的 Hchan* runtime·makechan_c(ChanType *t,int64 hint)
此时,hint=5,t=interface{}
它完成的任务就是:
分配hint * sizeof(t) + sizeof(Hchan)的内存空间[也就是说,buffered chan的buffer越大,占用
内存越大]
ch <- 5
就会调用 void runtime·chansend(ChanType *t,Hchan *chan,byte *ep,bool *pres)
}