liveBook · Manning

WaitGroup Done method

As explained in Learn Concurrent Programming with Go

A waitgroup Done operation decrements the count of outstanding operations tracked by a waitgroup.

A waitgroup Done operation decrements the count of outstanding operations by one. A goroutine calls Done after completing its task; when the count reaches zero, a goroutine blocked by Wait can continue. section 6.1.1 section 6.4

Use Done as the completion step in this lifecycle:

  • Add the number of expected tasks to the waitgroup before starting the work. section 6.1.1
  • Pass the waitgroup reference to each goroutine performing a task. section 6.1.1
  • Call Done after the goroutine finishes its assigned work. section 6.1.1
  • Let Wait remain blocked until every outstanding task has called Done. section 6.1.1

Four concurrent tasks

Create a waitgroup, call Add(4), and start four doWork goroutines. Each doWork function sleeps for a random duration, prints its completion, and calls wg.Done(); afterward, wg.Wait returns and the program prints "All complete". section 6.1.1

Listing 6.9 Done() operation for the waitgroup using condition variables
func (wg *WaitGrp) Done() {
    wg.cond.L.Lock()           #1
    wg.groupSize--             #2
    if wg.groupSize == 0 {
        wg.cond.Broadcast()    #3
    }
    wg.cond.L.Unlock()         #1
}
#1 Protects the update to the groupSize variable with a mutex lock
#2 Reduces the groupSize by 1
#3 If it’s the last goroutine to be done in the waitgroup, it broadcasts on the condition variable.

Inspect a condition-variable implementation showing Done locking the counter, decrementing groupSize, and broadcasting when the final task completes. section 6.1.4

How Learn Concurrent Programming with Go covers it

How deep it goes
Defines the decrement and traces its condition-variable internals, but stops short of broader synchronization failure modes.
Examples
Uses four delayed workers, recursive filename search, letter-frequency counting, semaphore waitgroups, and a custom condition-variable waitgroup.
What it assumes
Assumes goroutines and concurrent tasks while defining waitgroup counting through Add, Done, and Wait.
What you can do after
Apply it via Go's sync.WaitGroup to signal completed goroutines and release a goroutine waiting for all tasks.
How it connects
Connects Done with waitgroups, Wait, Add, goroutines, mutexes, condition variables, and semaphores.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.