From 7b6d3ffe549520ae5aaa36939f4240c14d07a988 Mon Sep 17 00:00:00 2001 From: structix Date: Sat, 21 Apr 2018 21:08:29 +0200 Subject: [PATCH] Fixed go routines syncing --- download.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/download.go b/download.go index 24cb340..ed74390 100644 --- a/download.go +++ b/download.go @@ -6,6 +6,7 @@ import ( "log" "os" "regexp" + "sync" //"path/filepath" . "github.com/kkdai/youtube" @@ -21,7 +22,7 @@ func NewBatch(batchFile, destinationDir string) *Batch { func (b *Batch) Start() { //Start downloading all videos - + log.Println("Start downloading...") //open the file containing yt links linkfile, err := os.Open(b.batchfile) if err != nil { @@ -34,18 +35,27 @@ func (b *Batch) Start() { //That should be enough for yt links. scanner := bufio.NewScanner(linkfile) + var wg sync.WaitGroup + for scanner.Scan() { //Call download - go downloadVideo(b.destDir, scanner.Text()) + log.Println(scanner.Text()) + //add go routine to wait for + wg.Add(1) + go downloadVideo(b.destDir, scanner.Text(), wg) } + //wait for all go routines to finish + wg.Wait() if err := scanner.Err(); err != nil { log.Fatal(err) } } -func downloadVideo(destDir, url string) { +func downloadVideo(destDir, url string, wg sync.WaitGroup) { // NewYoutube(debug) if debug parameter will set true we can log of messages + //defer Done() so that WaitGroup knows when the routine finishes + defer wg.Done() y := NewYoutube(false) y.DecodeURL(url) re := regexp.MustCompile("(mp4|webm|3gpp)")