Skip to content

Commit

Permalink
Refactor [Worker] [Captain] Fix Potential Issue of Deadlocks (#56)
Browse files Browse the repository at this point in the history
- [+] chore(captain.go): refactor shutdown function to use sync.Once for ensuring it is only called once
  • Loading branch information
H0llyW00dzZ authored Dec 30, 2023
1 parent a93b56a commit 6029bae
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions worker/captain.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
func CaptainTellWorkers(ctx context.Context, clientset *kubernetes.Clientset, shipsNamespace string, tasks []configuration.Task, workerCount int) (<-chan string, func()) {
results := make(chan string)
var wg sync.WaitGroup
var once sync.Once // Use sync.Once to ensure shutdown is only called once
taskStatus := NewTaskStatusMap() // Tracks the claiming of tasks to avoid duplication.

shutdownCtx, cancelFunc := context.WithCancel(ctx) // Derived context to signal shutdown.
Expand All @@ -42,13 +43,15 @@ func CaptainTellWorkers(ctx context.Context, clientset *kubernetes.Clientset, sh

// shutdown is called to initiate a graceful shutdown of all workers.
shutdown := func() {
cancelFunc() // Signal workers to stop by cancelling the context.

// Ensure channel closure happens after all workers have finished.
go func() {
wg.Wait() // Wait for all workers to complete.
close(results) // Close the results channel safely.
}()
once.Do(func() { // Ensure this block only runs once
cancelFunc() // Signal workers to stop by cancelling the context.

// Ensure channel closure happens after all workers have finished.
go func() {
wg.Wait() // Wait for all workers to complete.
close(results) // Close the results channel safely.
}()
})
}

return results, shutdown
Expand Down

0 comments on commit 6029bae

Please sign in to comment.