Skip to content

Instantly share code, notes, and snippets.

@nikolaiianchuk
Last active January 10, 2023 07:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nikolaiianchuk/19c661c189d37095fb5f3bbefbdaa65a to your computer and use it in GitHub Desktop.
Save nikolaiianchuk/19c661c189d37095fb5f3bbefbdaa65a to your computer and use it in GitHub Desktop.
Fixed memory leaking
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