Answer the question
In order to leave comments, you need to log in
Why is such code in golang not executed in parallel?
There is a code, according to all the rules, the results of the http request should be displayed first, and then the results of the calc function. But initially the result of the calc function is displayed, and then the result of the http request. With all this, the code is not executed in parallel, since according to my calculations, the execution time of the entire program is the execution time of the calc function and the http request separately.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
func main() {
t1 := time.Now()
t := make(chan int)
r := make(chan response)
go calc(t)
go request(r)
for i := 0; i < 2; i++ {
select {
case msg1 := <-t:
fmt.Println(msg1)
case msg2 := <-r:
fmt.Println(msg2)
}
}
fmt.Println("elapsedTime:", time.Now().Sub(t1))
}
type response struct {
URL string `json:"url"`
}
func request(str chan response) {
resp, err := http.Get("https://httpbin.org/get")
if err != nil {
log.Fatalln(err)
}
var result response
json.NewDecoder(resp.Body).Decode(&result)
str <- result
}
func calc(total chan int) {
var sum int
for i := 0; i < 4000000000; i++ {
sum += i
}
total <- sum
}
Answer the question
In order to leave comments, you need to log in
for i := 0; i < 4000000000; i++ {
sum += i
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question