parallel processing

This commit is contained in:
Celogeek 2022-12-26 20:54:47 +01:00
parent 5c44129fe7
commit 1563458214
Signed by: celogeek
GPG Key ID: E6B7BDCFC446233A

View File

@ -6,8 +6,10 @@ import (
"io/fs" "io/fs"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"sort" "sort"
"strings" "strings"
"sync"
"text/template" "text/template"
"time" "time"
@ -37,7 +39,7 @@ type EPub struct {
ViewHeight int ViewHeight int
Quality int Quality int
Images []Images Images []*Images
FirstImageTitle string FirstImageTitle string
Error error Error error
} }
@ -58,8 +60,6 @@ func NewEpub(path string) *EPub {
ViewWidth: 0, ViewWidth: 0,
ViewHeight: 0, ViewHeight: 0,
Quality: 75, Quality: 75,
Images: make([]Images, 0),
} }
} }
@ -137,17 +137,54 @@ func (e *EPub) LoadDir(dirname string) *EPub {
sort.Strings(images) sort.Strings(images)
titleFormat := fmt.Sprintf("%%0%dd", len(fmt.Sprint(len(images)-1))) titleFormat := fmt.Sprintf("%%0%dd", len(fmt.Sprint(len(images)-1)))
for i, path := range images {
fmt.Printf("Processing %d / %d\n", i+1, len(images)) wg := &sync.WaitGroup{}
data, w, h := imageconverter.Convert(path, true, e.ViewWidth, e.ViewHeight, e.Quality) wg.Add(runtime.NumCPU())
e.Images = append(e.Images, Images{
Id: i, type todoStruct struct {
Title: fmt.Sprintf(titleFormat, i), Id int
Data: data, Path string
Width: w,
Height: h,
})
} }
type resultStruct struct {
Id int
Data string
Width int
Height int
}
todo := make(chan *todoStruct)
result := make(chan *resultStruct)
for i := 0; i < runtime.NumCPU(); i++ {
go func() {
defer wg.Done()
for task := range todo {
data, w, h := imageconverter.Convert(task.Path, true, e.ViewWidth, e.ViewHeight, e.Quality)
result <- &resultStruct{task.Id, data, w, h}
}
}()
}
go func() {
for id, path := range images {
todo <- &todoStruct{id, path}
}
close(todo)
wg.Wait()
close(result)
}()
e.Images = make([]*Images, len(images))
for res := range result {
fmt.Printf("%d done\n", res.Id)
e.Images[res.Id] = &Images{
Id: res.Id,
Title: fmt.Sprintf(titleFormat, res.Id),
Data: res.Data,
Width: res.Width,
Height: res.Height,
}
}
e.FirstImageTitle = e.Images[0].Title e.FirstImageTitle = e.Images[0].Title
return e return e