使用sync.map和sync.cond封装消息队列,有哪些弊端和优点 | go | go 技术论坛-金年会app官方网
网络编程中,服务端接收客户端消息,读取出userid,把userid和msgbody关联起来,使用sync.map和sync.cond设计一个消息队列,这样的方式有啥弊端和优势,讨论讨论
type messagequeue struct {
msgmap sync.map
cond *sync.cond
}
func newmessagequeue() (msgqueue *messagequeue) {
msgqueue = &messagequeue{
msgmap: sync.map{},
cond: sync.newcond(new(sync.mutex)),
}
return
}
func (q *messagequeue) push(k any, v any) {
q.msgmap.store(k, v)
q.cond.broadcast()
}
func (q *messagequeue) pop(fn func(k, v any)) {
q.lock()
defer q.unlock()
q.wait()
q.msgmap.range(func(k, v any) bool {
fn(k, v)
q.msgmap.delete(k)
return true
})
}
func (q *messagequeue) load(k any, fn func(value any)) bool {
if v, ok := q.msgmap.load(k); ok {
fn(v)
return ok
}
return true
}
func (q *messagequeue) lock() {
q.cond.l.lock()
}
func (q *messagequeue) unlock() {
q.cond.l.unlock()
}
func (q *messagequeue) wait() {
q.cond.wait()
}
服务器重启或宕机就歇菜了
token 不行?这个搞?