協(xié)程(Goroutine)是與其他函數(shù)或方法同時運行的函數(shù)或方法投放∧卫幔可以認(rèn)為它是輕量級的線程。與線程相比跪呈,創(chuàng)建 Goroutine 的成本很小段磨。因此,Go 應(yīng)用程序可以有上千個 Goroutines 同時運行耗绿。
在函數(shù)或方法調(diào)用之前加上關(guān)鍵字 go
苹支,這樣便開啟了一個并發(fā)的 Goroutine。
package main
import (
"fmt"
)
func hello() {
fmt.Println("Hello world goroutine")
}
func main() {
go hello()
fmt.Println("main function")
}
go hello()
開啟了一個新的協(xié)程∥笞瑁現(xiàn)在 hello()
函數(shù)將和 main()
函數(shù)一起運行债蜜。main()
函數(shù)在單獨的協(xié)程中運行,這個協(xié)程稱為主協(xié)程究反。
運行上面的程序?qū)H輸出一行文本: main function
寻定。
原因:
當(dāng)創(chuàng)建一個 Go 協(xié)程時,創(chuàng)建這個 Go 協(xié)程的語句立即返回并向下繼續(xù)執(zhí)行精耐。與函數(shù)不同狼速,程序流程不會等待 Go 協(xié)程結(jié)束再繼續(xù)執(zhí)行。
在主協(xié)程存在時才能運行其他協(xié)程卦停,主協(xié)程終止則程序終止向胡,其他協(xié)程也將終止。
package main
import (
"fmt"
"time"
)
func hello() {
fmt.Println("Hello world goroutine")
}
func main() {
go hello()
time.Sleep(1 * time.Second)
fmt.Println("main function")
}
開啟多個協(xié)程:
package main
import (
"fmt"
"time"
)
func numbers() {
for i := 1; i <= 5; i++ {
time.Sleep(250 * time.Millisecond)
fmt.Printf("%d ", i)
}
}
func alphabets() {
for i := 'a'; i <= 'e'; i++ {
time.Sleep(400 * time.Millisecond)
fmt.Printf("%c ", i)
}
}
func main() {
go numbers()
go alphabets()
time.Sleep(3000 * time.Millisecond)
fmt.Println("main terminated")
}
下面的圖片描述了這個程序是如何工作的: