Skip to content

Commit f4b451b

Browse files
Refactor generateVariants function to use goroutines with WaitGroup for concurrent variant generation
1 parent 50b76d1 commit f4b451b

1 file changed

Lines changed: 29 additions & 12 deletions

File tree

internal/handlers/variants.go

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"log"
66
"path/filepath"
7+
"sync"
78

89
"github.com/Prateet-Github/worker-go/internal/ffmpeg"
910
)
@@ -14,21 +15,37 @@ func (h *VideoHandler) generateVariants(
1415
outputDir string,
1516
) error {
1617

17-
for _, rendition := range ffmpeg.Renditions {
18+
var wg sync.WaitGroup
19+
20+
errCh := make(chan error, len(ffmpeg.Renditions))
1821

19-
renditionDir := filepath.Join(
20-
outputDir,
21-
rendition.Name,
22-
)
22+
for _, rendition := range ffmpeg.Renditions {
23+
r := rendition
24+
25+
wg.Go(func() { // new syntax for WaitGroup in Go 1.25 intead of wg.Add(1) and defer wg.Done() & go func()
26+
renditionDir := filepath.Join(
27+
outputDir,
28+
r.Name,
29+
)
30+
31+
log.Printf("Generating %s...", r.Name)
32+
33+
if err := h.ffmpeg.GenerateVariant(
34+
ctx,
35+
inputPath,
36+
renditionDir,
37+
r,
38+
); err != nil {
39+
errCh <- err
40+
}
41+
})
42+
}
2343

24-
log.Printf("Generating %s...", rendition.Name)
44+
wg.Wait()
45+
close(errCh)
2546

26-
if err := h.ffmpeg.GenerateVariant(
27-
ctx,
28-
inputPath,
29-
renditionDir,
30-
rendition,
31-
); err != nil {
47+
for err := range errCh {
48+
if err != nil {
3249
return err
3350
}
3451
}

0 commit comments

Comments
 (0)