Skip to content

Instantly share code, notes, and snippets.

@chrismytton
Created September 20, 2012 20:48
Show Gist options
  • Save chrismytton/3758264 to your computer and use it in GitHub Desktop.
Save chrismytton/3758264 to your computer and use it in GitHub Desktop.
Goroutines

In ping.go the printer runs in a goroutine and the main thread is blocked by fmt.Scanln. As expected it prints ping, then pong.

In ping2.go the printer itself is blocking the main thread. When run it returns ping twice before returning a pong.

$ go run ping.go
ping
pong
ping
pong
^C

$ go run ping2.go
ping
ping
pong
ping
pong
package main
import(
"fmt"
"time"
)
func pinger(c chan<- string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan<- string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c <-chan string) {
for {
msg := <- c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}
func main() {
var c chan string = make(chan string)
go pinger(c)
go ponger(c)
// Printer is run in a goroutine
go printer(c)
var input string
fmt.Scanln(&input)
}
package main
import(
"fmt"
"time"
)
func pinger(c chan<- string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan<- string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c <-chan string) {
for {
msg := <- c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}
func main() {
var c chan string = make(chan string)
go pinger(c)
go ponger(c)
// Printer blocks the main thread
printer(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment