Golang 防止通道阻塞
Golang prevent channel from blocking
我正在构建一个使用 websockets 的服务器。
目前每个连接的客户端都使用两个 goroutines。一种用于阅读,一种用于写作。
writing 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
}
}
我正在构建一个使用 websockets 的服务器。
目前每个连接的客户端都使用两个 goroutines。一种用于阅读,一种用于写作。
writing 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
}
}