Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I wanted to test the performance of concurrent http request in Go against node.js:

package main

import (
  "fmt"
  "time"
  "strconv"
  "net/http"
)

var responseCounter = 0
var requestCounter = 0
var count=0
var ch = make(chan int)

func sendRequest(){
    go func() {
        requestCounter++
        url := "https://www.google.co.in/#q=search_" +strconv.Itoa(requestCounter)
        resp, err := http.Get(url)
        if err != nil {
            fmt.Printf("\nError",err)
        }
        defer resp.Body.Close()
        count++
        ch <- count
        sendRequest()
    }()
}

func main() {

    for i := 1; i<100; i++{
        sendRequest()
    }

    for {
        select {
            case r := <-ch:
                fmt.Printf("\nChannel ",r)
            case <-time.After(50 * time.Millisecond):
                //sendRequest()
        }
    }
}

When I run this code the CPU usage goes very high (around 90%). Is there something wrong with this code? Have I used the Goroutines correctly?

share|improve this question
    
but you start infinitely many goroutines in your sendRequest, no? –  akonsu Jan 9 at 16:29
    
I did so because I wanted the requests to be continuous. So when one http request is complete I made another request by calling sendRequest(). Is there a better way to achieve this? –  Sarita Jan 10 at 15:52
    
try to wait for the goroutine to finish and then start another one. I do not know what is going on... –  akonsu Jan 10 at 16:19
    
So many data races!! (go {build,install,run,test} -race is your friend). –  Dave C Apr 12 at 17:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.