S
S
Skelman2019-07-29 22:13:33
go
Skelman, 2019-07-29 22:13:33

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

1 answer(s)
D
Dmitry Shitskov, 2019-07-29
@Skelman

for i := 0; i < 4000000000; i++ {
    sum += i
  }

This code is too CPU-intensive, which prevents timely switching between goroutines. If you add even a small delay of a millisecond in this loop, everything will work as it should - while one goroutine is sleeping, another one will be executing.
If the Go version is <1.5 , most likely only 1 CPU core is used by default. Therefore, 1 highly loaded goroutine "interferes" with the work of all others.
In Go >= 1.5, this variable defaults to the number of processor cores/threads. You can also try to change the value of runtime.GOMAXPROCS yourself .
https://habr.com/ru/post/195574/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question