使用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()
}
讨论数量: 2

服务器重启或宕机就歇菜了

5小时前

token 不行?这个搞?

16分钟前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图