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
