From e34108a8d160186962e01d4539feeb7b225abf45 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Thu, 11 Oct 2012 07:52:36 -0700 Subject: [PATCH] publish goroutines --- examples.txt | 2 +- examples/goroutines/goroutines.go | 30 ++++++++++++++++++++++++++---- examples/goroutines/goroutines.sh | 17 +++++++++++++++++ 3 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 examples/goroutines/goroutines.sh diff --git a/examples.txt b/examples.txt index 737f1ce..bb9f78f 100644 --- a/examples.txt +++ b/examples.txt @@ -25,7 +25,7 @@ Maps # Interfaces # Errors # OK Guards -# Goroutines +Goroutines # Concurrent Goroutines # Channels # Channel Buffering diff --git a/examples/goroutines/goroutines.go b/examples/goroutines/goroutines.go index e0bc17e..98cd466 100644 --- a/examples/goroutines/goroutines.go +++ b/examples/goroutines/goroutines.go @@ -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") } diff --git a/examples/goroutines/goroutines.sh b/examples/goroutines/goroutines.sh new file mode 100644 index 0000000..4869383 --- /dev/null +++ b/examples/goroutines/goroutines.sh @@ -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 + +done + +# Next we'll look at a complement to goroutines in +# concurrent Go programs: channels.