goroutine是一個(gè)輕量級(jí)的執(zhí)行線程。
假設(shè)有一個(gè)函數(shù)調(diào)用f(s)。 下面是以通常的方式調(diào)用它,同步運(yùn)行它。
要在goroutine中調(diào)用此函數(shù),請(qǐng)使用go f(s)。 這個(gè)新的goroutine將與調(diào)用同時(shí)執(zhí)行。
也可以為匿名函數(shù)調(diào)用啟動(dòng)一個(gè)goroutine。
兩個(gè)函數(shù)調(diào)用現(xiàn)在在不同的goroutine中異步運(yùn)行,所以執(zhí)行到這里。這個(gè)ScanIn代碼要求我們?cè)诔绦蛲顺鲋鞍匆粋€(gè)鍵。
當(dāng)我們運(yùn)行這個(gè)程序時(shí),首先看到阻塞調(diào)用的輸出,然后是兩個(gè)gouroutines的交替輸出。 這種交替反映了Go運(yùn)行時(shí)并發(fā)運(yùn)行的goroutine。
接下來,我們來看看在并發(fā)Go程序中goroutines的一個(gè)補(bǔ)充:channels。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.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")
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
goroutine : 2
going
123456
done