• golang里channel的实现原理


    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的实现
        }
  • 相关阅读:
    Python--day68--ORM内容回顾
    Python--day67--include包含其他的url和反向解析URL
    Python--day67--Django的路由系统
    Python--day67--Jsonresponse响应介绍和路由系统的分组命名匹配方式(简单介绍)
    Python--day67--CBV和FBV、Request对象及上传文件示例
    Python--day66--Django模板语言关于静态文件路径的灵活写法
    GET和POST两种基本请求方法的区别
    ASP.NET中使用UpdatePanel实现局部异步刷新方法和攻略(转)
    GridView中实现DropDownList联动
    .NET string字符串的截取、移除、替换、插入
  • 原文地址:https://www.cnblogs.com/ExMan/p/14683989.html
Copyright © 2020-2023  润新知