Skip to content

Commit

Permalink
fix unexpected exit on download
Browse files Browse the repository at this point in the history
  • Loading branch information
Mrs4s authored May 21, 2022
1 parent 4c2c969 commit e624070
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@ func main() {
for _, task := range tasks {
c.Download(task)
}
c.WorkerPool.Wait()
}
13 changes: 10 additions & 3 deletions utils/worker.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package utils

import "fmt"
import (
"fmt"
"sync"
)

type TaskQueue chan *MultiThreadDownloader

Expand All @@ -9,6 +12,8 @@ type Worker struct {
}

type WorkerPool struct {
sync.WaitGroup

WorkerCount int
TaskQueue TaskQueue
WorkerQueue chan TaskQueue
Expand All @@ -26,7 +31,7 @@ func NewWorkerPool(WorkerCount int) *WorkerPool {
}
}

func (w *Worker) Run(wq chan TaskQueue) {
func (w *Worker) Run(wq chan TaskQueue, owner *WorkerPool) {
go func() {
for {
wq <- w.TaskChan
Expand All @@ -38,6 +43,7 @@ func (w *Worker) Run(wq chan TaskQueue) {
return
}
fmt.Println("下载完成", t.FullPath)
owner.Done()
}
}
}()
Expand All @@ -46,12 +52,13 @@ func (w *Worker) Run(wq chan TaskQueue) {
func (wp *WorkerPool) Start() {
for i := 0; i < wp.WorkerCount; i++ {
w := NewWorker()
w.Run(wp.WorkerQueue)
w.Run(wp.WorkerQueue, wp)
}
go func() {
for {
select {
case t := <-wp.TaskQueue:
wp.Add(1)
w := <-wp.WorkerQueue
w <- t
}
Expand Down

0 comments on commit e624070

Please sign in to comment.