Created
May 5, 2020 19:41
-
-
Save olehcambel/9384919a6512b7a726a05885a20d3801 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" | |
"net/http" | |
"time" | |
) | |
const maxOutstanding = 2 | |
var counter = 0 | |
func process(r *http.Request) { | |
time.Sleep(time.Second * 3) | |
} | |
func handle(queue <-chan *http.Request) { | |
for r := range queue { | |
process(r) | |
counter++ | |
fmt.Println(counter) | |
} | |
} | |
func serve(queue <-chan *http.Request) { | |
for i := 0; i < maxOutstanding; i++ { | |
go handle(queue) | |
} | |
} | |
func main() { | |
var queue = make(chan *http.Request) | |
go serve(queue) | |
http.HandleFunc("/go", func(res http.ResponseWriter, req *http.Request) { | |
queue <- req | |
}) | |
http.ListenAndServe(":3001", nil) | |
} |
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" | |
"net/http" | |
"time" | |
) | |
const maxOutstanding = 2 | |
var counter = 0 | |
var sem = make(chan int, maxOutstanding) | |
var queue = make(chan *http.Request) | |
func process(r *http.Request) { | |
time.Sleep(time.Second * 3) | |
} | |
func handle(r *http.Request) { | |
process(r) | |
counter++ | |
fmt.Println(counter) | |
<-sem | |
} | |
func serve(queue <-chan *http.Request) { | |
for req := range queue { | |
sem <- 1 | |
go handle(req) | |
} | |
} | |
func goHandler(res http.ResponseWriter, req *http.Request) { | |
queue <- req | |
} | |
func main() { | |
go serve(queue) | |
http.HandleFunc("/go", goHandler) | |
http.ListenAndServe(":3001", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment