当前位置: 代码网 > it编程>前端脚本>Golang > Golang通道阻塞情况与通道无阻塞实现小结

Golang通道阻塞情况与通道无阻塞实现小结

2024年05月15日 Golang 我要评论
一、通道阻塞原理在go语言中,通道会在以下情况下发生阻塞:如果通道已满,并且没有协程在读取通道中的数据,那么任何试图将数据写入通道的协程都会被阻塞,直到有空间可用为止。如果通道为空,并且没有协程在等待

一、通道阻塞原理

在go语言中,通道会在以下情况下发生阻塞:

  • 如果通道已满,并且没有协程在读取通道中的数据,那么任何试图将数据写入通道的协程都会被阻塞,直到有空间可用为止。
  • 如果通道为空,并且没有协程在等待从通道中读取数据,那么任何试图从通道中读取数据的协程都会被阻塞,直到有数据可用为止。

二、通道阻塞场景

在channel中,无论是有缓存通道、无缓冲通道都存在阻塞的情况。阻塞场景共4个,有缓存和无缓冲各2个。

2.1 无缓冲通道

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

  • 通道中无数据,但执行读通道。
  • 通道中无数据,向通道写数据,但无协程读取。
// 场景1
func readnodatafromnobufch() {
    nobufch := make(chan int)

    <-nobufch
    fmt.println("read from no buffer channel success")

    // output:
    // fatal error: all goroutines are asleep - deadlock!
}

// 场景2
func writenobufch() {
    ch := make(chan int)

    ch <- 1
    fmt.println("write success no block")
    
    // output:
    // fatal error: all goroutines are asleep - deadlock!
}

注:示例代码中的output注释代表函数的执行结果

每一个函数都由于阻塞在通道操作而无法继续向下执行,最后报了死锁错误。

2.2 有缓存通道

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

  • 通道的缓存无数据,但执行读通道。
  • 通道的缓存已经占满,向通道写数据,但无协程读。
// 场景1
func readnodatafrombufch() {
    bufch := make(chan int, 1)

    <-bufch
    fmt.println("read from no buffer channel success")

    // output:
    // fatal error: all goroutines are asleep - deadlock!
}

// 场景2
func writebufchbutfull() {
    ch := make(chan int, 1)
    // make ch full
    ch <- 100

    ch <- 1
    fmt.println("write success no block")
    
    // output:
    // fatal error: all goroutines are asleep - deadlock!
}

三、通道无阻塞读写

3.1 select实现无阻塞读写

下面示例代码是使用select修改后的无缓冲通道和有缓冲通道的读写,以下函数可以直接通过main函数调用;

// 1.select结构实现通道读
func readwithselect(ch chan int) (x int, err error) {
    select {
    case x = <-ch:
        return x, nil
    default:
        return 0, errors.new("channel has no data")
    }
}

// 无缓冲通道读
func readnodatafromnobufchwithselect() {
    bufch := make(chan int)

    if v, err := readwithselect(bufch); err != nil {
        fmt.println(err)
    } else {
        fmt.printf("read: %d\n", v)
    }

    // output:
    // channel has no data
}

// 有缓冲通道读
func readnodatafrombufchwithselect() {
    bufch := make(chan int, 1)

    if v, err := readwithselect(bufch); err != nil {
        fmt.println(err)
    } else {
        fmt.printf("read: %d\n", v)
    }

    // output:
    // channel has no data
}

// 2. select结构实现通道写
func writechwithselect(ch chan int) error {
    select {
    case ch <- 1:
        return nil
    default:
        return errors.new("channel blocked, can not write")
    }
}

// 无缓冲通道写
func writenobufchwithselect() {
    ch := make(chan int)
    if err := writechwithselect(ch); err != nil {
        fmt.println(err)
    } else {
        fmt.println("write success")
    }

    // output:
    // channel blocked, can not write
}

// 有缓冲通道写
func writebufchbutfullwithselect() {
    ch := make(chan int, 1)
    // make ch full
    ch <- 100
    if err := writechwithselect(ch); err != nil {
        fmt.println(err)
    } else {
        fmt.println("write success")
    }

    // output:
    // channel blocked, can not write
}

注:示例代码中的output注释代表函数的执行结果

从结果能看出,在通道不可读或者不可写的时候,不再阻塞等待,而是直接返回。

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

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

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

func readwithselect(ch chan int) (x int, err error) {
    timeout := time.newtimer(time.microsecond * 500)

    select {
    case x = <-ch:
        return x, nil
    case <-timeout.c:
        return 0, errors.new("read time out")
    }
}

func writechwithselect(ch chan int) error {
    timeout := time.newtimer(time.microsecond * 500)

    select {
    case ch <- 1:
        return nil
    case <-timeout.c:
        return errors.new("write time out")
    }
}

结果就会变成超时返回:

read time out
write time out
read time out
write time out

四、总结

本篇文章介绍了在go语言中,通道会在以下情况下发生阻塞:

  • 如果通道已满,并且没有协程在读取通道中的数据,那么任何试图将数据写入通道的协程都会被阻塞,直到有空间可用为止。
  • 如果通道为空,并且没有协程在等待从通道中读取数据,那么任何试图从通道中读取数据的协程都会被阻塞,直到有数据可用为止。

以及解决阻塞的2种办法:

  • 使用select的default语句,在channel不可读写时,即可返回
  • 使用select+定时器,在超时时间内,channel不可读写,则返回

五、参考链接

到此这篇关于golang通道阻塞情况与通道无阻塞实现小结的文章就介绍到这了,更多相关golang通道阻塞情况与通道无阻塞内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com