Created
December 16, 2020 17:55
-
-
Save tejo/cf5e2658bcc58f59306a30b71c2bdeeb to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"log" | |
"net/http" | |
"runtime" | |
"time" | |
) | |
type jobInput struct { | |
/* ... */ | |
} | |
type jobOutput struct { | |
/* ... */ | |
} | |
func process(j jobInput) jobOutput { | |
time.Sleep(2 * time.Second) | |
log.Println("CONVERT") | |
return jobOutput{} // | |
} | |
type Job struct { | |
in jobInput | |
out chan<- jobOutput | |
} | |
var jobs = make(chan Job, 100) | |
func worker() { | |
for { | |
elt := <-jobs | |
elt.out <- process(elt.in) | |
} | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
var j jobInput | |
o := make(chan jobOutput) | |
jobs <- Job{j, o} | |
jobOutput := <-o | |
_ = jobOutput | |
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path) | |
} | |
func main() { | |
concurrentJobs := runtime.NumCPU() - 1 | |
for i := 0; i < concurrentJobs; i++ { | |
go worker() | |
fmt.Printf("Start worker n %d\n", i+1) | |
} | |
http.HandleFunc("/convert", handler) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment