前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一招教你无阻塞读写Golang channel

一招教你无阻塞读写Golang channel

作者头像
李海彬
发布2018-12-25 16:22:26
8710
发布2018-12-25 16:22:26
举报
文章被收录于专栏:Golang语言社区Golang语言社区

原文作者:shitaibin 链接:https://www.jianshu.com/p/3b24e909905f 來源:简书

无论是无缓冲通道,还是有缓冲通道,都存在阻塞的情况,教你一招再也不遇到channel阻塞的问题。

这篇文章会介绍,哪些情况会存在阻塞,以及如何使用select解决阻塞。

阻塞场景

阻塞场景共4个,有缓存和无缓冲各2个。

无缓冲通道的特点是,发送的数据需要被读取后,发送才会完成,它阻塞场景:

  1. 通道中无数据,但执行读通道。
  2. 通道中无数据,向通道写数据,但无协程读取。
代码语言:javascript
复制
 1// 场景1
 2func ReadNoDataFromNoBufCh() {
 3    noBufCh := make(chan int)
 4
 5    <-noBufCh
 6    fmt.Println("read from no buffer channel success")
 7
 8    // Output:
 9    // fatal error: all goroutines are asleep - deadlock!
10}
11
12// 场景2
13func WriteNoBufCh() {
14    ch := make(chan int)
15
16    ch <- 1
17    fmt.Println("write success no block")
18
19    // Output:
20    // fatal error: all goroutines are asleep - deadlock!
21}

注:示例代码中的Output注释代表函数的执行结果,每一个函数都由于阻塞在通道操作而无法继续向下执行,最后报了死锁错误。

有缓存通道的特点是,有缓存时可以向通道中写入数据后直接返回,缓存中有数据时可以从通道中读到数据直接返回,这时有缓存通道是不会阻塞的,它阻塞的场景是:

  1. 通道的缓存无数据,但执行读通道。
  2. 通道的缓存已经占满,向通道写数据,但无协程读。
代码语言:javascript
复制
 1// 场景1
 2func ReadNoDataFromBufCh() {
 3    bufCh := make(chan int, 1)
 4
 5    <-bufCh
 6    fmt.Println("read from no buffer channel success")
 7
 8    // Output:
 9    // fatal error: all goroutines are asleep - deadlock!
10}
11
12// 场景2
13func WriteBufChButFull() {
14    ch := make(chan int, 1)
15    // make ch full
16    ch <- 100
17
18    ch <- 1
19    fmt.Println("write success no block")
20
21    // Output:
22    // fatal error: all goroutines are asleep - deadlock!
23}

使用Select实现无阻塞读写

select是执行选择操作的一个结构,它里面有一组case语句,它会执行其中无阻塞的那一个,如果都阻塞了,那就等待其中一个不阻塞,进而继续执行,它有一个default语句,该语句是永远不会阻塞的,我们可以借助它实现无阻塞的操作。

下面示例代码是使用select修改后的无缓冲通道和有缓冲通道的读写,以下函数可以直接通过main函数调用,其中的Ouput的注释是运行结果,从结果能看出,在通道不可读或者不可写的时候,不再阻塞等待,而是直接返回。

代码语言:javascript
复制
 1// 无缓冲通道读
 2func ReadNoDataFromNoBufChWithSelect() {
 3    bufCh := make(chan int)
 4
 5    if v, err := ReadWithSelect(bufCh); err != nil {
 6        fmt.Println(err)
 7    } else {
 8        fmt.Printf("read: %d\n", v)
 9    }
10
11    // Output:
12    // channel has no data
13}
14
15// 有缓冲通道读
16func ReadNoDataFromBufChWithSelect() {
17    bufCh := make(chan int, 1)
18
19    if v, err := ReadWithSelect(bufCh); err != nil {
20        fmt.Println(err)
21    } else {
22        fmt.Printf("read: %d\n", v)
23    }
24
25    // Output:
26    // channel has no data
27}
28
29// select结构实现通道读
30func ReadWithSelect(ch chan int) (x int, err error) {
31    select {
32    case x = <-ch:
33        return x, nil
34    default:
35        return 0, errors.New("channel has no data")
36    }
37}
38
39// 无缓冲通道写
40func WriteNoBufChWithSelect() {
41    ch := make(chan int)
42    if err := WriteChWithSelect(ch); err != nil {
43        fmt.Println(err)
44    } else {
45        fmt.Println("write success")
46    }
47
48    // Output:
49    // channel blocked, can not write
50}
51
52// 有缓冲通道写
53func WriteBufChButFullWithSelect() {
54    ch := make(chan int, 1)
55    // make ch full
56    ch <- 100
57    if err := WriteChWithSelect(ch); err != nil {
58        fmt.Println(err)
59    } else {
60        fmt.Println("write success")
61    }
62
63    // Output:
64    // channel blocked, can not write
65}
66
67// select结构实现通道写
68func WriteChWithSelect(ch chan int) error {
69    select {
70    case ch <- 1:
71        return nil
72    default:
73        return errors.New("channel blocked, can not write")
74    }
75}

使用Select+超时改善无阻塞读写

使用default实现的无阻塞通道阻塞有一个缺陷:当通道不可读或写的时候,会即可返回。实际场景,更多的需求是,我们希望,尝试读一会数据,或者尝试写一会数据,如果实在没法读写,再返回,程序继续做其它的事情。

使用定时器替代default可以解决这个问题。比如,我给通道读写数据的容忍时间是500ms,如果依然无法读写,就即刻返回,修改一下会是这样:

代码语言:javascript
复制
 1func ReadWithSelect(ch chan int) (x int, err error) {
 2    timeout := time.NewTimer(time.Microsecond * 500)
 3
 4    select {
 5    case x = <-ch:
 6        return x, nil
 7    case <-timeout.C:
 8        return 0, errors.New("read time out")
 9    }
10}
11
12func WriteChWithSelect(ch chan int) error {
13    timeout := time.NewTimer(time.Microsecond * 500)
14
15    select {
16    case ch <- 1:
17        return nil
18    case <-timeout.C:
19        return errors.New("write time out")
20    }
21}

结果就会变成超时返回:

代码语言:javascript
复制
1read time out
2write time out
3read time out
4write time out

版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-12-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 阻塞场景
  • 使用Select实现无阻塞读写
  • 使用Select+超时改善无阻塞读写
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档