S
S
Skelman2019-07-26 12:21:07
go
Skelman, 2019-07-26 12:21:07

How to run multiple goroutines in parallel?

I can't get this code to work in parallel.
Who knows what I'm doing wrong?

package main

import (
  "fmt"
  "time"
)

func main() {
  t1 := time.Now()
  s1 := make(chan int)
  s2 := make(chan int)
  s3 := make(chan int)

  go summ1(s1)
  go summ2(s2)
  go summ3(s3)

  r1 := <-s1
  r2 := <-s2
  r3 := <-s3

  fmt.Println(r1)
  fmt.Println(r2)
  fmt.Println(r3)

  fmt.Println("elapsedTime:", time.Now().Sub(t1))
}

func summ1(summ chan int) {
  var sum int
  for i := 0; i < 1000000000; i++ {
    sum += i
  }
  summ <- sum
}

func summ2(summ chan int) {
  var sum int
  for i := 0; i < 1000000001; i++ {
    sum += i
  }
  summ <- sum
}

func summ3(summ chan int) {
  var sum int
  for i := 0; i < 1000000002; i++ {
    sum += i
  }
  summ <- sum
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nur Kutlugallyamov, 2019-07-26
@nur_ke2

"The number of running Machines is limited by the GOMAXPROCS environment variable or the runtime.GOMAXPROCS(n int) function. It defaults to 1. It usually makes sense to set it to the number of cores."
One machine - one goroutine.
https://habr.com/ru/post/141853/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question