-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy paththread.go
More file actions
45 lines (39 loc) · 1.35 KB
/
thread.go
File metadata and controls
45 lines (39 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package queue
import "sync"
// routineGroup is a thin wrapper around sync.WaitGroup for managing goroutine lifecycles.
// It simplifies the common pattern of spawning goroutines and waiting for their completion.
//
// Design rationale:
// - Encapsulates WaitGroup.Add(1) + go func() + defer Done() into a single Run() call
// - Reduces boilerplate and prevents common mistakes (forgetting to call Done, wrong Add count)
// - Provides a cleaner API for goroutine management in the queue implementation
type routineGroup struct {
waitGroup sync.WaitGroup
}
// newRoutineGroup creates a new routineGroup for managing goroutines.
func newRoutineGroup() *routineGroup {
return new(routineGroup)
}
// Run launches a goroutine to execute the provided function.
// The function is automatically registered with the WaitGroup and will be
// tracked until it completes. This method is safe to call concurrently.
//
// Example:
//
// rg := newRoutineGroup()
// rg.Run(func() {
// // Do work in background
// })
// rg.Wait() // Wait for all goroutines to complete
func (g *routineGroup) Run(fn func()) {
g.waitGroup.Add(1)
go func() {
defer g.waitGroup.Done()
fn()
}()
}
// Wait blocks until all goroutines launched via Run() have completed.
// This method is safe to call multiple times and from multiple goroutines.
func (g *routineGroup) Wait() {
g.waitGroup.Wait()
}