【问题标题】:Golang prevent channel from blockingGolang 防止通道阻塞
【发布时间】:2015-04-22 11:05:45
【问题描述】:

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

基本上,我希望在缓冲区已满时进行错误处理,而不是阻塞。 我怎样才能做到最好?

【问题讨论】:

标签: concurrency go channel


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 2017-12-08
    • 2016-07-06
    • 2017-06-07
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多