Created
December 3, 2018 11:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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