登录
首页 >  Golang >  Go问答

在并发环境下使用单个互斥锁

来源:stackoverflow

时间:2024-03-03 22:27:25 247浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《在并发环境下使用单个互斥锁》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我正在尝试减少我的 discord 机器人发出的 http 请求量。

它正在从 api 读取。

利用获取的数据更新内部数据库并输出更改。

事情是:对于机器人所在的每个服务器,该数据库都是不同的,这就是我使用 go 例程的地方。但是,有些服务器需要获取相同的数据,这就是我想减少http请求的地方。现在,无论我是否已经获取了角色,我都会发出请求。我想创建某种可以在 go 例程之间共享的数据,然后在此数据中进行请求搜索。

有人建议我使用互斥体。我想。原始问题:在 golang 中使用无缓冲通道

我制作了我尝试过的真实代码的框架:https://play.golang.org/p/mt229ns1r8m

在此示例中,master := make([][]map[string]interface{}, 0) 正在模拟不一致服务器。 charschars2 将是每个单独服务器的跟踪字符。 字符“test”对于它们来说是共同的,因此应该只从 api 中获取一次。

它输出:

[[map[level:15 name:test] map[level:150 name:test2]] [map[level:1500 name:test3] map[level:15 name:test]]]
------
a call would be made
a call would be made
a call would be made
a call would be made
cache: [map[level:150 name:test2] map[level:15 name:test]]cache: [map[level:15 name:test] map[level:1500 name:test3]]done

我期望的输出是:

[[map[Level:15 Name:Test] map[Level:150 Name:Test2]] [map[Level:1500 Name:Test3] map[Level:15 Name:Test]]]
------
A call would be made
A call would be made
A call would be made
Cache: [map[Level:150 Name:Test2] map[Level:15 Name:Test] map[Level:1500 Name:Test3]]Done

但是每个 go 例程都会生成一个新的缓存。我怎样才能解决这个问题? 谢谢。


解决方案


这里有太多的未知数,我无法真正编写出正确的设计,但让我们做一些注释:

  • 如果可能的话,尽量不要使用 interface{}。在这种情况下,似乎它一定是可能的,尽管我不确定实际类型是什么。

  • 尝试使您的数据尽可能简单,但不能更简单。在这种情况下,可能意味着:有一个数据结构用于“与 discord 服务器对话的事物”,并有一个单独的数据结构用于“与本地数据库对话的事物”(这是一个缓存数据库吗?如果是这样,使缓存条目无效的标准是什么?)。但是,如果一个“字符”(无论是什么——显然是一个字符串)在每个 discord 服务器上可以具有不同的属性,则意味着您在本地数据库中的索引不仅仅是一个字符,而是一对值:字符串值本身加上一个discord服务器标识符。

这可能会给你一个像这样的功能界面:

var cacheserver *cacheserver

func initcacheserver() error {
    cacheserver = ... // whatever it takes to initialize the cache server
}

(我假设了缓存服务器的延迟初始化。如果您可以进行预先初始化,则可以放弃下面的下一个测试。将 valuetype 替换为缓存名称查找结果的类型。)

func (discordserver ds) get(name string) (valuetype, error) {
    if cacheserver == nil {
        if err := initcacheserver(); err != nil {
            return nil, err
        }
    }
    // do a cache lookup.  tell the cache server that if there
    // is no entry, it should return a noentry error and we will
    // fill the cache ourselves, so it should hold this slot as
    // "will be filled, so wait for it".
    slot, v, err := cacheserver.lookup(name, ds.identity, cacheserver.intenttofill)

    if err == cacheserver.noentry {
        // we have the slot held.  try to look up the right info
        // directly in the discord server, then cache it.
        v, err = ds.uncachedget(name)
        // tell cache server that this is the value, or that it should
        // produce this error instead of nocache.
        cacheserver.fillslot(slot, v, err)
    }
}

您可能只想缓存一些错误类型,而不是全部;这是另一个设计问题,需要我在这里无法提供的答案。还有其他方法可以做到这一点,但也不一定需要 slot 指针返回值;我刚刚选择了这个作为示例。

请注意,现在大部分“艰苦工作”都在缓存服务器中进行,这肯定需要一些花哨的技巧。特别是,您需要锁定整个数据结构一段时间,用它来找到正确的槽,然后保留该槽本身,以便该槽的其他用户必须等待,同时释放整个锁,以便 其他条目无需等待。这引入了锁定顺序约束:小心避免死锁。一种可行的方法是:

type cacheserver struct {
    lock sync.mutex
    data map[string]map[string]*entry
    // more fields
}

type entry {
    lock        sync.mutex
    cachedvalue valuetype
    cachederror error
}

(您将需要更多类型,例如下面的 intent,现​​在仅需要两个枚举整数,上面可能还需要更多字段;​​这只是一个骨架。)

func (cs *CacheServer) Lookup(name, srv string, flags Intent) (*Entry, ValueType, error) {
    cs.lock.Lock()
    defer cs.lock.Unlock()
    // first, look up the server - if it does not exist, create one
    smap := cs.data[srv]
    if smap == nil {
        cs.data[server] = make(map[string]*Entry)
    }
    entry := smap[name]
    if entry == nil {
        // no cached entry - if this is a pure lookup, just error,
        // but if not, make a locked entry
        if flags == CacheServer.IntentToFill {
            // make a new entry and return with it locked
            entry = &Entry{}
            smap[name] = entry
            entry.lock.Lock() // and do not unlock
        }
        return entry, nil, NoEntry
    }
    entry.lock.Lock() // wait for someone to fill it, if needed
    defer entry.lock.Unlock()
    return nil, entry.cachedValue, entry.cachedError
}

您还需要一个例程来填充和释放条目,但这非常简单。如果您选择,可以将此方法设为 entry 类型而不是 cacheserver 类型,因为至少在这个特定原型中,不需要直接使用缓存服务器数据结构。不过,如果您开始对缓存失效更加感兴趣,那么访问 cacheserver 对象可能会更好。

注意:我这样设计是为了让您可以在没有意图填充的情况下进行缓存查找(如果这有用的话)。如果不是,就没有理由费心 intent 参数。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在并发环境下使用单个互斥锁》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>