【Golang】singleflight 源码注释

在引入本地 cache 的场景下,缓存失效回源时会将请求打到后台数据库,在高并发时会带来性能和稳定性隐患。

singleflight 能够使多个并发请求所触发的回源操作里,只有第一个回源被执行,其余请求阻塞等待第一个被执行的那个回源操作完成后,直接取其结果,以此保证同一时刻只有一个回源操作在执行,以达到防止击穿的效果。

源码注释如下:

// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package singleflight provides a duplicate function call suppression mechanism.
package singleflight

import "sync"

// call is an in-flight or completed singleflight.Do call
// call 代表一个正在执行或已完成的函数调用。
type call struct {

    wg sync.WaitGroup    // 用于阻塞调用这个 call 的其他请求

    // 这两个字段在 WaitGroup.Done() 之前被写入(仅写一次),并在 WaitGroup.Done() 之后被读取。
    val interface{} // 函数执行后的结果
    err error          // 函数执行后的error

    // These fields are read and written with the singleflight mutex held before the WaitGroup is done,  
    // and are read but not written after the WaitGroup is done.
    dups  int
    chans []chan<- Result
}


// Group represents a class of work and forms a namespace in 
// which units of work can be executed with duplicate suppression.
type Group struct {
    mu sync.Mutex       // 保护锁
    m  map[string]*call // 懒加载
}

// Result holds the results of Do, so they can be passed on a channel.
type Result struct {
    Val    interface{}
    Err    error
    Shared bool
}

// Do executes and returns the results of the given function, making
// sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results.
// The return value shared indicates whether v was given to multiple callers.

// 在 Do 函数中,函数先是判断这个 key 是否是第一次调用,如果是,就会进入 doCall 调用回调函数获取结果,
// 后续的请求就会阻塞在 c.wg.Wait() 这里,等待回调函数返回以后,直接拿到结果。
func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
    

    // 有可能要修改 g.m ,所以先上锁进行保护
    g.mu.Lock()
    
     // key-call 映射表不存在就创建(懒加载)
    if g.m == nil {
        g.m = make(map[string]*call)
    }

     // 如果 g.m 中已经存在对该 key 的请求,则新协程不会重复处理 key 的请求 ,所以释放锁,然后阻塞等待已存的 key 请求得到的结果。
    if c, ok := g.m[key]; ok {
        // 释放 mu 锁并 wait 在 wg 上,在 wg.wait() 返回后,把结果返回。
        c.dups++
        g.mu.Unlock()
        // 如果已存的 key 请求完成,阻塞状态会解除,wg.Wait() 返回
        c.wg.Wait()
        return c.val, c.err, true
    }


     // 如果没有在处理,则创建一个 call ,把 wg 加 1,把 call 存到 m 中表示已经有在请求了,然后释放锁
    c := new(call)
    c.wg.Add(1)
    g.m[key] = c
    g.mu.Unlock()

    // 执行真正的请求函数,得到对该 key 请求的结果
    g.doCall(c, key, fn)

    // 返回请求结果
    return c.val, c.err, c.dups > 0
}

// DoChan is like Do but returns a channel that will receive the
// results when they are ready. The second result is true if the function
// will eventually be called, false if it will not (because there is
// a pending request with this key).
func (g *Group) DoChan(key string, fn func() (interface{}, error)) (<-chan Result, bool) {
    ch := make(chan Result, 1)

    // 有可能要修改 g.m ,所以先上锁进行保护
    g.mu.Lock()
    // key-call 映射表不存在就创建(懒加载)
    if g.m == nil {
        g.m = make(map[string]*call)
    }
    // 如果 g.m 中已经存在对该 key 的请求,则新协程不会重复处理 key 的请求 ,所以释放锁,然后阻塞等待已存的 key 请求得到的结果。
    if c, ok := g.m[key]; ok {
        c.dups++
        c.chans = append(c.chans, ch) // 追加 chan 用来接收返回结果
        g.mu.Unlock()
        return ch, false
    }
    // 如果没有在处理,则创建一个 call ,把 wg 加 1,把 call 存到 m 中表示已经有在请求了,然后释放锁
    c := &call{chans: []chan<- Result{ch}}
    c.wg.Add(1)
    g.m[key] = c
    g.mu.Unlock()

    go g.doCall(c, key, fn)

    return ch, true
}

// doCall handles the single call for a key.
func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
    
    // 执行 fn,记录结果到 c.val, c.err 中
    c.val, c.err = fn()

    // 释放 wg,会唤醒外部的 wg.wait() 阻塞
    c.wg.Done()

    // 共享变量 g.m 的写保护
    g.mu.Lock()

    // 删除 key 
    delete(g.m, key)

    // 结果递送
    for _, ch := range c.chans {
        ch <- Result{c.val, c.err, c.dups > 0}

    g.mu.Unlock()
}

// ForgetUnshared tells the singleflight to forget about a key if it is not
// shared with any other goroutines. Future calls to Do for a forgotten key
// will call the function rather than waiting for an earlier call to complete.
// Returns whether the key was forgotten or unknown--that is, whether no
// other goroutines are waiting for the result.
func (g *Group) ForgetUnshared(key string) bool {
    g.mu.Lock()
    defer g.mu.Unlock()
    c, ok := g.m[key]
    if !ok {
        return true
    }
    if c.dups == 0 {
        delete(g.m, key)
        return true
    }
    return false
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335