分享
  1. 首页
  2. 文章

golang里channel的实现原理

funkygao · · 2846 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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的实现
}


有疑问加站长微信联系(非本文作者)

本文来自:新浪博客

感谢作者:funkygao

查看原文:golang里channel的实现原理

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
2846 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏