publish goroutines

This commit is contained in:
Mark McGranaghan 2012-10-11 07:52:36 -07:00
parent dfee14d4da
commit e34108a8d1
3 changed files with 44 additions and 5 deletions

View File

@ -25,7 +25,7 @@ Maps
# Interfaces
# Errors
# OK Guards
# Goroutines
Goroutines
# Concurrent Goroutines
# Channels
# Channel Buffering

View File

@ -1,15 +1,37 @@
// A _goroutine_ is a lightweight thread of execution.
package main
import "fmt"
func f(n int) {
for i := 0; i < 10; i++ {
fmt.Println(n, ":", i)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
go f(0)
// Suppose we have a function call `f(s)`. Here's how
// we'd call that in the usual way, running it inline.
f("direct")
// To invoke this function in a goroutine, use
// `go f(s)`. This will start a new, concurrently
// executing goroutine.
go f("goroutine")
// You can also start a goroutine for an anonymous
// function.
go func() {
fmt.Println("going")
}()
// Since our two goroutines are running asynchrously
// in separate goroutines now, execution immediatly
// falls through to here. This `Scanln` code requires
// that we press a key before the program exits.
var input string
fmt.Scanln(&input)
fmt.Println("done")
}

View File

@ -0,0 +1,17 @@
# When we run this program, we see the output of the
# direct call first, then the interleaved output of the
# two gouroutines. This interleaving reflects the
# goroutines being run concurrently by the Go runtime.
$ go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
<enter>
done
# Next we'll look at a complement to goroutines in
# concurrent Go programs: channels.