繁体   English   中英

Golang阻止通道阻塞

[英]Golang prevent channel from blocking

我正在构建一个使用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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM