...
Code Block |
---|
package main import ( "fmt" ) func main(){ //run in background go count("sheep") go count("fish") //wait for keyboard press before exiting fmt.Scanln() } func count(thing string) { for i:=0; true; i++ { fmt.Println(i, thing) time.Sleep(time.Millisecond * 500) } } |
Using Channels
Channels are blocking
Code Block |
---|
package main
import (
"fmt"
"time"
)
func main(){
//make channel of type string
c := make(chan,string)
//run in background
go count("sheep", c)
//block until message is pushed to the channel
msg:= <- c
fmt.Println(msg)
}
func count(thing string, c chan string) {
for i:=0; i <= 5; i++ {
//send message on channel
c <- thing
time.Sleep(time.Millisecond * 500)
}
} |
In the above code, the program exits once the count routine returns a message on the channel.
References
Reference | URL |
---|---|
Learn Go in 12 Minutes | https://www.youtube.com/watch?v=C8LgvuEBraI |
Go Packages | https://golang.org/pkg/ |
Go By Examples | https://gobyexample.com/ |
...