-
-
Save deadprogram/71e6ceac5129db5188bf9c382939f018 to your computer and use it in GitHub Desktop.
Fixed memory leaking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"runtime" | |
"time" | |
"gocv.io/x/gocv" | |
) | |
type Pool struct { | |
JobChan chan Job | |
} | |
func NewPool(maxRoutines, chanLen int) *Pool { | |
p := new(Pool) | |
p.JobChan = make(chan Job, chanLen) | |
for i := 0; i < maxRoutines; i++ { | |
go func() { | |
runtime.LockOSThread() | |
defer runtime.UnlockOSThread() | |
for job := range p.JobChan { | |
job.Process() | |
} | |
}() | |
} | |
return p | |
} | |
type Job interface { | |
Process() | |
} | |
type ImageWork struct { | |
ImageBytes []byte | |
} | |
func (i *ImageWork) Process() { | |
DecodeAndClose(i.ImageBytes) | |
} | |
var jobQueue chan Job | |
func main() { | |
pool := NewPool(runtime.GOMAXPROCS(0), 100) | |
jobQueue = pool.JobChan | |
fmt.Println("Started") | |
http.HandleFunc("/file", FileHandler) | |
http.ListenAndServe(":8080", nil) | |
} | |
func FileHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Println(time.Now(), "FileHander") | |
r.ParseMultipartForm(2 << 20) | |
_, h, err := r.FormFile("file") | |
if err != nil { | |
fmt.Fprintln(w, err) | |
} | |
f, err := h.Open() | |
i := &ImageWork{} | |
i.ImageBytes, err = ioutil.ReadAll(f) | |
if err != nil { | |
fmt.Fprintln(w, err) | |
} | |
f.Close() | |
jobQueue <- i | |
fmt.Fprintln(w, "ok") | |
} | |
func DecodeAndClose(b []byte) { | |
m, err := gocv.IMDecode(b, gocv.IMReadUnchanged) | |
if err != nil { | |
fmt.Println(err) | |
} | |
gocv.IMWrite("/img/test.jpg", m) | |
m.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment