Skip to content

Instantly share code, notes, and snippets.

@oktalz
Created December 3, 2018 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oktalz/74ce0768272cc7b25c3e3849e0ec471e to your computer and use it in GitHub Desktop.
Save oktalz/74ce0768272cc7b25c3e3849e0ec471e to your computer and use it in GitHub Desktop.
Go example, go version 1.11, what happens with GC if we have a goroutine that is intensive
package main
import (
"log"
"runtime"
"time"
)
func example1() {
//this example locks all threads
go func() {
for {
//doing something intensive
}
}()
go func() {
i := 0
for {
i++
log.Println("random text", i)
time.Sleep(time.Millisecond * 10)
//doing something that include, for instance, writing to disc
runtime.Gosched() //just to make sure that this does not block
}
}()
log.Println("Hi gophers")
runtime.Gosched() //force running of goroutine, example needs to be short
log.Println("at one point GC kicks in")
// and were are stuck here forever
// both routines are stuck after some random text printing
runtime.GC()
// we never reach here
log.Println("Bye all")
}
func example2() {
go func() {
for {
runtime.Gosched()
}
}()
go func() {
i := 0
for {
i++
log.Println("random text", i)
time.Sleep(time.Millisecond * 10)
//runtime.Gosched() //we do not need that here
}
}()
log.Println("Hi gophers")
runtime.Gosched() //force running of goroutine
log.Println("at one point GC kicks in")
runtime.GC()
log.Println("Bye all")
//all ok :)
}
func example3() {
go func() {
for {
//runtime.Gosched()
}
}()
go func() {
i := 0
for {
i++
log.Println("random text", i)
time.Sleep(time.Millisecond * 10)
}
}()
log.Println("Hi gophers")
runtime.Gosched() //force running of goroutine
log.Println("no GC call")
log.Println("Bye all")
// no GC, all ok, we exit
}
func main() {
/*log.Println("\n----------\nWithout GC\n----------")
example3() /* */
/*log.Println("\n----------\nWith GC but no block\n----------")
example2() /* */
log.Println("\n----------\nWith GC but block in go <= v1.11\n----------")
example1() /* */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment