
goroutines
the most simple go routine can be done as
01func a(string s) {
02 fmt.println(a)
03}
04
05func main() {
06 go a("a")
07 go a("b")
08 go a("c")
09
10 do_something()
11}as soon as go a() is executed, a new goroutine is created and it just runs async from the main() function. the main() goes back to executing the next statement without caring about the results of the goroutine.
since these processes are just generated off from main, if main completes executing before the go a(), we would not see the result of that goroutine.
1func a(string s) {
2 fmt.println(a)
3}
4
5func main() {
6 go a("a")
7}this code will often print nothing since main terminates immediately.
channels
used to communicate data between goroutines. since the main function is a goroutine, channels can be used to get informtion from any goroutine inside it.
1func main() {
2 channel := make(chan string)
3 go func() {
4 channel <- data
5 }()
6
7 msg := <- channel
8 fmt.Println(msg)
9}select is going to block until one of the channels inside it return something, and then executes the corresponsing block. if both return at the same time, it is selected at random
1select {
2 case msgfromchannel1 := <- channel1:
3 fmt.Println("channel 1")
4 case msgfromchannel2 := <- channel2:
5 fmt.Println("channel 2")
6}