脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - go select编译期的优化处理逻辑使用场景分析

go select编译期的优化处理逻辑使用场景分析

2021-08-11 01:14yuchenfw Golang

select 是 Go 中的一个控制结构,类似于用于通信的 switch 语句。每个 case 必须是一个通信操作,要么是发送要么是接收。接下来通过本文给大家介绍go select编译期的优化处理逻辑使用场景分析,感兴趣的朋友一起看看吧

前言

select作为Go chan通信的重要监听工具,有着很广泛的使用场景。select的使用主要是搭配通信case使用,表面上看,只是简单的selectcase搭配,实际上根据case的数量及类型,在编译时select会进行优化处理,根据不同的情况调用不同的底层逻辑。

select的编译处理

select编译时的核心处理逻辑如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
func walkselectcases(cases *Nodes) []*Node {
    ncas := cases.Len()
    sellineno := lineno
 
    // optimization: zero-case select
    // 针对没有case的select优化
    if ncas == 0 {
        return []*Node{mkcall("block", nil, nil)}
    }
 
    // optimization: one-case select: single op.
    // 针对1个case(单个操作)select的优化
    if ncas == 1 {
        cas := cases.First()
        setlineno(cas)
        l := cas.Ninit.Slice()
        if cas.Left != nil { // not default: 非default case
            n := cas.Left // 获取case表达式
            l = append(l, n.Ninit.Slice()...)
            n.Ninit.Set(nil)
            switch n.Op {
            default:
                Fatalf("select %v", n.Op)
 
            case OSEND: // Left <- Right
                // already ok
                // n中已包含left/right
            
            case OSELRECV, OSELRECV2: // OSELRECV(Left = <-Right.Left) OSELRECV2(List = <-Right.Left)
                if n.Op == OSELRECV || n.List.Len() == 0 { // 左侧有0或1个接收者
                    if n.Left == nil { // 没有接收者
                        n = n.Right // 只需保留右侧
                    } else { //
                        n.Op = OAS // 只有一个接收者,更新Op为OAS
                    }
                    break
                }
 
                if n.Left == nil { // 检查是否表达式或赋值
                    nblank = typecheck(nblank, ctxExpr|ctxAssign)
                    n.Left = nblank
                }
 
                n.Op = OAS2 // OSELRECV2多个接收者
                n.List.Prepend(n.Left) // 将left放在前面
                n.Rlist.Set1(n.Right)
                n.Right = nil
                n.Left = nil
                n.SetTypecheck(0)
                n = typecheck(n, ctxStmt)
            }
 
            l = append(l, n)
        }
 
        l = append(l, cas.Nbody.Slice()...) // case内的处理
        l = append(l, nod(OBREAK, nil, nil)) // 添加break
        return l
    }
 
    // convert case value arguments to addresses.
    // this rewrite is used by both the general code and the next optimization.
    var dflt *Node
    for _, cas := range cases.Slice() {
        setlineno(cas)
        n := cas.Left
        if n == nil {
            dflt = cas
            continue
        }
        switch n.Op {
        case OSEND:
            n.Right = nod(OADDR, n.Right, nil)
            n.Right = typecheck(n.Right, ctxExpr)
 
        case OSELRECV, OSELRECV2:
            if n.Op == OSELRECV2 && n.List.Len() == 0 {
                n.Op = OSELRECV
            }
 
            if n.Left != nil {
                n.Left = nod(OADDR, n.Left, nil)
                n.Left = typecheck(n.Left, ctxExpr)
            }
        }
    }
 
    // optimization: two-case select but one is default: single non-blocking op.
    if ncas == 2 && dflt != nil {
        cas := cases.First()
        if cas == dflt {
            cas = cases.Second()
        }
 
        n := cas.Left
        setlineno(n)
        r := nod(OIF, nil, nil)
        r.Ninit.Set(cas.Ninit.Slice())
        switch n.Op {
        default:
            Fatalf("select %v", n.Op)
 
        case OSEND:
            // if selectnbsend(c, v) { body } else { default body }
            ch := n.Left
            r.Left = mkcall1(chanfn("selectnbsend", 2, ch.Type), types.Types[TBOOL], &r.Ninit, ch, n.Right)
 
        case OSELRECV:
            // if selectnbrecv(&v, c) { body } else { default body }
            ch := n.Right.Left
            elem := n.Left
            if elem == nil {
                elem = nodnil()
            }
            r.Left = mkcall1(chanfn("selectnbrecv", 2, ch.Type), types.Types[TBOOL], &r.Ninit, elem, ch)
 
        case OSELRECV2:
            // if selectnbrecv2(&v, &received, c) { body } else { default body }
            ch := n.Right.Left
            elem := n.Left
            if elem == nil {
                elem = nodnil()
            }
            receivedp := nod(OADDR, n.List.First(), nil)
            receivedp = typecheck(receivedp, ctxExpr)
            r.Left = mkcall1(chanfn("selectnbrecv2", 2, ch.Type), types.Types[TBOOL], &r.Ninit, elem, receivedp, ch)
        }
 
        r.Left = typecheck(r.Left, ctxExpr)
        r.Nbody.Set(cas.Nbody.Slice())
        r.Rlist.Set(append(dflt.Ninit.Slice(), dflt.Nbody.Slice()...))
        return []*Node{r, nod(OBREAK, nil, nil)}
    }
 
    if dflt != nil {
        ncas--
    }
    casorder := make([]*Node, ncas)
    nsends, nrecvs := 0, 0
 
    var init []*Node
 
    // generate sel-struct
    lineno = sellineno
    selv := temp(types.NewArray(scasetype(), int64(ncas)))
    r := nod(OAS, selv, nil)
    r = typecheck(r, ctxStmt)
    init = append(init, r)
 
    // No initialization for order; runtime.selectgo is responsible for that.
    order := temp(types.NewArray(types.Types[TUINT16], 2*int64(ncas)))
 
    var pc0, pcs *Node
    if flag_race {
        pcs = temp(types.NewArray(types.Types[TUINTPTR], int64(ncas)))
        pc0 = typecheck(nod(OADDR, nod(OINDEX, pcs, nodintconst(0)), nil), ctxExpr)
    } else {
        pc0 = nodnil()
    }
 
    // register cases
    for _, cas := range cases.Slice() {
        setlineno(cas)
 
        init = append(init, cas.Ninit.Slice()...)
        cas.Ninit.Set(nil)
 
        n := cas.Left
        if n == nil { // default:
            continue
        }
 
        var i int
        var c, elem *Node
        switch n.Op {
        default:
            Fatalf("select %v", n.Op)
        case OSEND:
            i = nsends
            nsends++
            c = n.Left
            elem = n.Right
        case OSELRECV, OSELRECV2:
            nrecvs++
            i = ncas - nrecvs
            c = n.Right.Left
            elem = n.Left
        }
 
        casorder[i] = cas
 
        setField := func(f string, val *Node) {
            r := nod(OAS, nodSym(ODOT, nod(OINDEX, selv, nodintconst(int64(i))), lookup(f)), val)
            r = typecheck(r, ctxStmt)
            init = append(init, r)
        }
 
        c = convnop(c, types.Types[TUNSAFEPTR])
        setField("c", c)
        if elem != nil {
            elem = convnop(elem, types.Types[TUNSAFEPTR])
            setField("elem", elem)
        }
 
        // TODO(mdempsky): There should be a cleaner way to
        // handle this.
        if flag_race {
            r = mkcall("selectsetpc", nil, nil, nod(OADDR, nod(OINDEX, pcs, nodintconst(int64(i))), nil))
            init = append(init, r)
        }
    }
    if nsends+nrecvs != ncas {
        Fatalf("walkselectcases: miscount: %v + %v != %v", nsends, nrecvs, ncas)
    }
 
    // run the select
    lineno = sellineno
    chosen := temp(types.Types[TINT])
    recvOK := temp(types.Types[TBOOL])
    r = nod(OAS2, nil, nil)
    r.List.Set2(chosen, recvOK)
    fn := syslook("selectgo")
    r.Rlist.Set1(mkcall1(fn, fn.Type.Results(), nil, bytePtrToIndex(selv, 0), bytePtrToIndex(order, 0), pc0, nodintconst(int64(nsends)), nodintconst(int64(nrecvs)), nodbool(dflt == nil)))
    r = typecheck(r, ctxStmt)
    init = append(init, r)
 
    // selv and order are no longer alive after selectgo.
    init = append(init, nod(OVARKILL, selv, nil))
    init = append(init, nod(OVARKILL, order, nil))
    if flag_race {
        init = append(init, nod(OVARKILL, pcs, nil))
    }
 
    // dispatch cases
    dispatch := func(cond, cas *Node) {
        cond = typecheck(cond, ctxExpr)
        cond = defaultlit(cond, nil)
 
        r := nod(OIF, cond, nil)
 
        if n := cas.Left; n != nil && n.Op == OSELRECV2 {
            x := nod(OAS, n.List.First(), recvOK)
            x = typecheck(x, ctxStmt)
            r.Nbody.Append(x)
        }
 
        r.Nbody.AppendNodes(&cas.Nbody)
        r.Nbody.Append(nod(OBREAK, nil, nil))
        init = append(init, r)
    }
 
    if dflt != nil {
        setlineno(dflt)
        dispatch(nod(OLT, chosen, nodintconst(0)), dflt)
    }
    for i, cas := range casorder {
        setlineno(cas)
        dispatch(nod(OEQ, chosen, nodintconst(int64(i))), cas)
    }
 
    return init
}

select编译时会根据case的数量进行优化:

1.没有case
直接调用block

2.1个case
(1)default case,直接执行body
(2) send/recv case (block为true),按照单独执行的结果确认,可能会发生block
(3) send调用对应的chansend1
(4) recv调用对应的chanrecv1/chanrecv2

3.2个case且包含一个default case
(1) send/recv case (block为false),按照单独执行的结果确认case是否ok,!ok则执行default case,不会发生block
(2) send调用对应的selectnbsend
(3) recv调用对应的selectnbrecv/selectnbrecv2

4.一般的case
selectgo

总结

最后,以一张图进行简单总结。

go select编译期的优化处理逻辑使用场景分析

以上就是go select编译期的优化处理逻辑使用场景分析的详细内容,更多关于go select编译的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/xz_studying/article/details/118280886

延伸 · 阅读

精彩推荐
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7812021-12-05
  • GolangGO语言字符串处理Strings包的函数使用示例讲解

    GO语言字符串处理Strings包的函数使用示例讲解

    这篇文章主要为大家介绍了GO语言字符串处理Strings包的函数使用示例讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加...

    Jeff的技术栈6882022-04-14
  • Golang深入浅析Go中三个点(...)用法

    深入浅析Go中三个点(...)用法

    这篇文章主要介绍了深入浅析Go中三个点(...)用法,需要的朋友可以参考下...

    踏雪无痕SS6472021-11-17
  • GolangGolang实现四种负载均衡的算法(随机,轮询等)

    Golang实现四种负载均衡的算法(随机,轮询等)

    本文介绍了示例介绍了Golang 负载均衡的四种实现,主要包括了随机,轮询,加权轮询负载,一致性hash,感兴趣的小伙伴们可以参考一下...

    Gundy_8442021-08-09
  • Golanggo语言获取系统盘符的方法

    go语言获取系统盘符的方法

    这篇文章主要介绍了go语言获取系统盘符的方法,涉及Go语言调用winapi获取系统硬件信息的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    无尽海3862020-04-24
  • GolangGolang 语言极简类型转换库cast的使用详解

    Golang 语言极简类型转换库cast的使用详解

    本文我们通过 cast.ToString() 函数的使用,简单介绍了cast 的使用方法,除此之外,它还支持很多其他类型,在这没有多多介绍,对Golang 类型转换库 cast相关知...

    Golang语言开发栈6112021-12-02
  • GolangGo语言range关键字循环时的坑

    Go语言range关键字循环时的坑

    今天小编就为大家分享一篇关于Go语言range关键字循环时的坑,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来...

    benben_20154202020-05-23
  • GolangGo语言实现自动填写古诗词实例代码

    Go语言实现自动填写古诗词实例代码

    这篇文章主要给大家介绍了关于Go语言实现自动填写古诗词的相关资料,这是最近在项目中遇到的一个需求,文中通过示例代码介绍的非常详细,需要的朋...

    FengY5862020-05-14