Is starting Goroutines heavy for the machine?


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #1

Hi there

Are you using for different “database queries” of Goroutines?
I tried this on “database queries”, My mean is one “Goroutine” for “update” one for “insert” etc…
it’s was slower than “simple func”
so in below code why “simple func” is faster than “goRoutines func”?

Here is playGround :
https://play.golang.org/p/E5AJvwdKyqb

Also code review :

package main

import (
	p "fmt"
	w "sync"
	t "time"
)

var wg w.WaitGroup
func main() {
	simple(200)
	goRoutines(200)
}

simple function :

func simple(n int) {
	startTime := t.Now().UnixNano()
	for i:=0;i< n;i++ {
		 gen(10, 50, 100, 200)
	}

	p.Println("simple     : ",t.Now().UnixNano()-startTime)
}

func gen(n ...int) {
	var slice []int
	for _, k := range n {
			slice = append(slice, k*10+50/2)
		}
}

Goroutines function :

func goRoutines(n int)  {
	startTime := t.Now().UnixNano()
	wg.Add(n)

	for i:=0;i< n;i++ {
		go gen2(10, 50, 100, 200)
	}

	wg.Wait()
	p.Println("goRoutines : ",t.Now().UnixNano()-startTime)
}

func gen2(n ...int) {
	var slice []int
	for _, k := range n {
		slice = append(slice, k*10+50/2)
	}
	wg.Done()
}

result :

simple : 49033794
goRoutines : 65791173

Thanks in Advance.


(Johan Dahl) #2

The problem why your go routine version is slower is because go-routines runs until it encounters a blocking call like waiting for disk, network and similar. So running a go routine inside a tight loop will not give any time to other go routines unless you have more than one core so they can run in parallell.

Read more here https://codeburst.io/why-goroutines-are-not-lightweight-threads-7c460c1f155

Don’t interrupt!

The go runtime scheduler does cooperative scheduling, which means another goroutine will only be scheduled if the current one is blocking or done. Some of these cases are:

  • Channel send and receive operations, if those operations would block.
  • The Go statement, although there is no guarantee that new goroutine will be scheduled immediately.
  • Blocking syscalls like file and network operations.
  • After being stopped for a garbage collection cycle.

(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #3

thanks, Johan
the link is Broken ( Read more here https://codeburst.io/why-goroutines-are-not-lightweight-threads-7c460c1f155 )


(Johan Dahl) #4

Strange. By clicking on the link here doesn’t work but then I search for it on google I come to the page and it still has the same address :confused:

Try this: https://www.google.se/search?q=Why+goroutines+are+not+lightweight+threads

here is also some links: http://www.golangbootcamp.com/book/concurrency especially Rob Pikes talk concurrency is not parallism is very interesting.


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #5

np thank u so much