golang里channel的实现原理

来源:互联网 发布:vr培训机构 知乎 编辑:程序博客网 时间:2024/06/13 08:30
channel是消息传递的机制,用于多线程环境下lock free synchronization.
它同时具备2个特性:
1. 消息传递
2. 同步

golang里的channel的性能,可以参考前一篇:http://blog.sina.com.cn/s/blog_630c58cb01016xur.html
此外,自带的runtime package里已经提供了benchmark代码,可以运行下面的命令查看其性能:
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
BenchmarkChanProdConsWork0      1000000          1874 ns/op
BenchmarkChanProdConsWork10     1000000          1805 ns/op
BenchmarkChanProdConsWork100    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)
    lock(chan)
    如果chan是buffer chan {
        比较当前已经放入buffer里的数据是否满了A
        如果没有满 {
            把ep(要放入到chan里的数据)拷贝到chan的内存区域 (此区域是sender/recver共享的)
            找到receiver goroutine, make it ready, and schedule it to recv
        } else {
            已经满了
            把当前goroutine状态设置为Gwaiting
            yield
        }

    } else {
        // 这是blocked chan
        找到receiver goroutine (channel的隐喻就是一定存在多个goroutine)
        让该goroutine变成ready (之前是Gwaiting), 从而参与schedule,获得控制权
        具体执行什么,要看chanrecv的实现
    }

0 0