加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

并发 – Golang阻止通道阻塞

发布时间:2020-12-16 09:23:49 所属栏目:大数据 来源:网络整理
导读:我正在构建一个使用websockets的服务器. 目前,每个连接的客户端都使用两个goroutine.一个用于阅读,一个用于写作. 写作goroutine基本上会收听它应该发送的消息的频道,然后尝试传递它们. type User struct{ send chan []byte ...}func (u *User) Send(msg []by
我正在构建一个使用websockets的服务器.
目前,每个连接的客户端都使用两个goroutine.一个用于阅读,一个用于写作.
写作goroutine基本上会收听它应该发送的消息的频道,然后尝试传递它们.

type User struct{
    send chan []byte
    ...
}

func (u *User) Send(msg []byte){
    u.send <- msg
}

问题是,来自客户端A的读取可能导致写入客户端B.
假设与B的连接存在一些问题(例如非常慢)并且它的发送通道已经满了.目前的行为是,尝试向频道添加消息现在开始阻止,直到从频道中删除某些内容.
这意味着,现在A等待B的缓冲区不再满.

我想解决它有点像这样:

func (u *User) Send(msg []byte) err{
    u.send,err <- msg
    if err != nil{
        //The channels buffer is full.
        //Writing currently not possible.
        //Needs appropriate error handling.
        return err
    }
    return nil
}

基本上不是阻塞我想要缓冲区已满的错误处理.
我如何做到最好?

解决方法

正如ThunderCat在他的评论中指出的那样,解决方案是

func (u *User) Send(msg []byte){
    select{
    case u.send <- msg:
    default: //Error handling here
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读