Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task: Remove unnecessary calls to defer g.mu.Unlock() #12710

Merged
merged 8 commits into from
Jan 18, 2024
22 changes: 10 additions & 12 deletions lxd/task/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
//
// All tasks in a group will be started and stopped at the same time.
type Group struct {
cancel func()
cancel context.CancelFunc
wg sync.WaitGroup
tasks []Task
running map[int]bool
Expand All @@ -22,16 +22,15 @@ type Group struct {
// Add a new task to the group, returning its index.
func (g *Group) Add(f Func, schedule Schedule) *Task {
g.mu.Lock()
defer g.mu.Unlock()

i := len(g.tasks)
g.tasks = append(g.tasks, Task{
f: f,
schedule: schedule,
reset: make(chan struct{}, 16), // Buffered to not block senders
})
t := &g.tasks[len(g.tasks)-1] // Get the task we added to g.tasks.
g.mu.Unlock()

return &g.tasks[i]
return t
}

// Start all the tasks in the group.
Expand All @@ -40,7 +39,6 @@ func (g *Group) Start(ctx context.Context) {
// concurrent calls to Start() or Add(0) don't race. This ensures all tasks in this group
// are started based on a consistent snapshot of g.running and g.tasks.
g.mu.Lock()
defer g.mu.Unlock()

ctx, g.cancel = context.WithCancel(ctx)
g.wg.Add(len(g.tasks))
Expand All @@ -60,16 +58,17 @@ func (g *Group) Start(ctx context.Context) {
go func(i int) {
task.loop(ctx)

// Ensure running map is updated before wait group Done() is called.
g.mu.Lock()
defer g.mu.Unlock()

if g.running != nil {
tomponline marked this conversation as resolved.
Show resolved Hide resolved
// Ensure running map is updated before wait group Done() is called.
g.mu.Lock()
g.running[i] = false
g.mu.Unlock()
g.wg.Done()
}
}(i)
}

g.mu.Unlock()
}

// Stop all tasks in the group.
Expand Down Expand Up @@ -106,14 +105,13 @@ func (g *Group) Stop(timeout time.Duration) error {
select {
case <-ctx.Done():
g.mu.Lock()
defer g.mu.Unlock()

running := []string{}
for i, value := range g.running {
if value {
running = append(running, strconv.Itoa(i))
}
}
g.mu.Unlock()

return fmt.Errorf("Task(s) still running: IDs %v", running)
case <-graceful:
Expand Down
Loading