I've been trying to solve this problem for a long time I really can't see the cause.. The thing is I am calling a goroutine n times, which has to leave some result in a channel. This goroutines perform a post request to some website with a Client. The thing is that it looks like they have to wait for each other, since their times (the time for the function to finish) look like this in the output: 1s 2s 3s 5s . .
and so on; when they're supposed to run concurrently.
Here it goes the important pieces of the code.
First, the calling function. This is supposed to trigger a "getFlight" for every id, and keep gathering the information they return through the channel. postUrl and urlParams are pre-assigned variables, a string and a pointer, respectively. The copy of the client is simply cause I thought that using the same client could've been the reason for the serialization, but looks like not.
result := []types.Trip{}
c := make(chan types.Trip)
for _, id := range ids {
client1 := *client
client2 := &client1
go getFlight(id, postUrl, urlParams, client2, c)
}
for range ids {
result = append(result, <-c)
}
return result
And this is the part of getFlight where I make the http request. All the variables have been previously initialized.
func getFlight(id string, postUrl string, urlParams *url.Values, client*http.Client, c chan types.Trip)
var newTrip types.Trip
newTrip.Url = postUrl
newTrip.UrlParams = *urlParams
r, err := http.NewRequest("POST", myUrl, bytes.NewBufferString(form.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
resp, err := client.Do(r)
if err != nil {
return
}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
As I said, the output of getFlight time, for every thread, looks like this:
4.6196584s 5.8934936s 7.1387969s 8.3415495s 9.7005444s 11.078563s 12.1587691s 13.8861763s
There's just not any kind of concurrency, and I really don't know why... And all the functions are starting at the same time, just put a Println at the very beggining of getFlight and all where shown at the same time.
Thanks for your help.
EDIT: The problem is indeed when calling client.Do(r), I put the timers before and after the call, and I get the same timings (1s, 2s, 3s, 5s..), therefore there is where the threads are waiting for the previous thread to finish. The question is, why?