go - What is correct way to use goroutine? -
i need apply tests each request , fire responce based on result of tests. if 1 of test fail, need send responce imediatelly, otherwise wait when tests done succesfully. want tests concurrency.
now, (simplified):
func handler_request_checker(w http.responsewriter, r *http.request) { done := make(chan bool) quit := make(chan bool) counter := 0 go testone(r,done,quit) go testtwo(r,done,quit) .............. go testten(r,done,quit) { select { case <- quit: fmt.println("got quit signal") return case <- done: counter++ if counter == 10 { fmt.println("all checks passed succesfully") return } } } func main() { http.handlefunc("/", handler_request_checker) http.listenandserve() }
example of 1 of goroutine:
func testone(r *http.request, done,quit chan bool) { ip,_,ok := net.splithostport(r.remoteaddr) if ok == nil { _,item := range bad_ip_list { if strings.contains(ip,item) { quit <- true return } } done <- true return } else { quit <- true return } }
problem goroutines doesnt' free memory after go t quit signal. suppose happens because there in done chanel. i'm new in go, maybe use them wrong way?
for example, when start load check http_load -parallel 10 -seconds 10
, goroutine eats 100+ mb of ram , dont'g give system. on next check, eat 100+ mb more, , on.
if tests without go
(step-by-step), program takes no more 10-15mb load checks.
your guess right. using synchronous channels, means both sender , receiver must available in order transmit value.
once handler_request_checker
function gets quit signal, stops retrieving values of done
, quit
channel. further testone
, testtwo
, etc. goroutines blocked when try send result. worse, stay in memory forever because still running since haven't transmitted result yet.
one way solve problem use buffered (asynchronous) channels done
, quit
. example:
done := make(chan bool, 10) quit := make(chan bool, 10)
if use buffer size of 10 10 tests, goroutines able send results, when there no reader available anymore. goroutines exit cleanly , channels (that might contain unread results) garbage collected once goroutines have quit.
Comments
Post a Comment