sync.WaitGroup

整體來說比較正常司恳,就是保存三個(gè)狀態(tài)

  1. 計(jì)數(shù)值 // add到了多少
  2. waiter數(shù)量 // 有多少調(diào)用了Wait方法
  3. seme // 用來阻塞的信號(hào)量,掛載等待的協(xié)程
    只是為了節(jié)省內(nèi)存徽职,這三個(gè)字段合成了一個(gè)字段,三個(gè)uint32切片共96位剧蹂。針對(duì)32位和64位系統(tǒng)也有不同實(shí)現(xiàn)爆安。
  • Add 方法主要操作的是 state 的計(jì)數(shù)部分氢烘。計(jì)數(shù)值增加一個(gè) delta 值怀偷,內(nèi)部通過原子操作把這個(gè)值加到計(jì)數(shù)值上。需要注意的是播玖,這個(gè) delta 也可以是個(gè)負(fù)數(shù)椎工,相當(dāng)于為計(jì)數(shù)值減去一個(gè)值,Done 方法內(nèi)部其實(shí)就是通過Add(-1) 實(shí)現(xiàn)的黎棠。
  • Wait 方法的實(shí)現(xiàn)邏輯是:不斷檢查 state 的值。如果其中的計(jì)數(shù)值變?yōu)榱?0镰绎,那么說明所有的任務(wù)已完成脓斩,調(diào)用者不必再等待,直接返回畴栖。如果計(jì)數(shù)值大于 0随静,說明此時(shí)還有任務(wù)沒完成,那么調(diào)用者就變成了等待者吗讶,需要加入 waiter 隊(duì)列燎猛,并且阻塞住自己。

Add的代碼

// Add adds delta, which may be negative, to the WaitGroup counter.
// If the counter becomes zero, all goroutines blocked on Wait are released.
// If the counter goes negative, Add panics.
//
// Note that calls with a positive delta that occur when the counter is zero
// must happen before a Wait. Calls with a negative delta, or calls with a
// positive delta that start when the counter is greater than zero, may happen
// at any time.
// Typically this means the calls to Add should execute before the statement
// creating the goroutine or other event to be waited for.
// If a WaitGroup is reused to wait for several independent sets of events,
// new Add calls must happen after all previous Wait calls have returned.
// See the WaitGroup example.
func (wg *WaitGroup) Add(delta int) {
    statep, semap := wg.state()
    if race.Enabled {
        _ = *statep // trigger nil deref early
        if delta < 0 {
            // Synchronize decrements with Wait.
            race.ReleaseMerge(unsafe.Pointer(wg))
        }
        race.Disable()
        defer race.Enable()
    }
    state := atomic.AddUint64(statep, uint64(delta)<<32)
    v := int32(state >> 32)
    w := uint32(state)
    if race.Enabled && delta > 0 && v == int32(delta) {
        // The first increment must be synchronized with Wait.
        // Need to model this as a read, because there can be
        // several concurrent wg.counter transitions from 0.
        race.Read(unsafe.Pointer(semap))
    }
    if v < 0 {
        panic("sync: negative WaitGroup counter")
    }
    if w != 0 && delta > 0 && v == int32(delta) {
        panic("sync: WaitGroup misuse: Add called concurrently with Wait")
    }
    if v > 0 || w == 0 {
        return
    }
    // This goroutine has set counter to 0 when waiters > 0.
    // Now there can't be concurrent mutations of state:
    // - Adds must not happen concurrently with Wait,
    // - Wait does not increment waiters if it sees counter == 0.
    // Still do a cheap sanity check to detect WaitGroup misuse.
    if *statep != state {
        panic("sync: WaitGroup misuse: Add called concurrently with Wait")
    }
    // Reset waiters count to 0.
    *statep = 0
    for ; w != 0; w-- {
        runtime_Semrelease(semap, false, 0)
    }
}

Wait的代碼


// Wait blocks until the WaitGroup counter is zero.
func (wg *WaitGroup) Wait() {
    statep, semap := wg.state()
    if race.Enabled {
        _ = *statep // trigger nil deref early
        race.Disable()
    }
    for {
        state := atomic.LoadUint64(statep)
        v := int32(state >> 32)
        w := uint32(state)
        if v == 0 {
            // Counter is 0, no need to wait.
            if race.Enabled {
                race.Enable()
                race.Acquire(unsafe.Pointer(wg))
            }
            return
        }
        // Increment waiters count.
        if atomic.CompareAndSwapUint64(statep, state, state+1) {
            if race.Enabled && w == 0 {
                // Wait must be synchronized with the first Add.
                // Need to model this is as a write to race with the read in Add.
                // As a consequence, can do the write only for the first waiter,
                // otherwise concurrent Waits will race with each other.
                race.Write(unsafe.Pointer(semap))
            }
            runtime_Semacquire(semap)
            if *statep != 0 {
                panic("sync: WaitGroup is reused before previous Wait has returned")
            }
            if race.Enabled {
                race.Enable()
                race.Acquire(unsafe.Pointer(wg))
            }
            return
        }
    }
}

需要注意的就是所有的Add要在Wait前調(diào)用 (在源碼中也有狀態(tài)的檢查)照皆。比如Add的調(diào)用要在開啟新協(xié)程前完成

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末重绷,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子膜毁,更是在濱河造成了極大的恐慌昭卓,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瘟滨,死亡現(xiàn)場離奇詭異候醒,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)杂瘸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門倒淫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人败玉,你說我怎么就攤上這事敌土。” “怎么了运翼?”我有些...
    開封第一講書人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵纯赎,是天一觀的道長。 經(jīng)常有香客問我南蹂,道長犬金,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮晚顷,結(jié)果婚禮上峰伙,老公的妹妹穿的比我還像新娘。我一直安慰自己该默,他們只是感情好瞳氓,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著栓袖,像睡著了一般匣摘。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上裹刮,一...
    開封第一講書人閱讀 52,262評(píng)論 1 308
  • 那天音榜,我揣著相機(jī)與錄音,去河邊找鬼捧弃。 笑死赠叼,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的违霞。 我是一名探鬼主播嘴办,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼买鸽!你這毒婦竟也來了涧郊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤眼五,失蹤者是張志新(化名)和其女友劉穎底燎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體弹砚,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡双仍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了桌吃。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片朱沃。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖茅诱,靈堂內(nèi)的尸體忽然破棺而出逗物,到底是詐尸還是另有隱情,我是刑警寧澤瑟俭,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布翎卓,位于F島的核電站,受9級(jí)特大地震影響摆寄,放射性物質(zhì)發(fā)生泄漏失暴。R本人自食惡果不足惜坯门,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逗扒。 院中可真熱鬧古戴,春花似錦、人聲如沸矩肩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽黍檩。三九已至叉袍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間刽酱,已是汗流浹背喳逛。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肛跌,地道東北人艺配。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓察郁,卻偏偏與公主長得像衍慎,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子皮钠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容