記錄goroutine相關用法
複製代碼
在golang中使用goroutine很簡單,經過go 關鍵字便可使用,例如:golang
func C(a chan struct{}){
<- a
fmt.Println("C()!")
}
複製代碼
其實多個goroutine執行是無序的,要想他們以必定的順序執行,能夠經過channel(使用 chan關鍵詞)來規劃他們。bash
完整案例1
package main
import (
"fmt"
"time"
)
func main(){
testrun := true
f := func() {
for testrun{
fmt.Println("sub proc running ...")
time.Sleep(1 * time.Second)
}
fmt.Println("sub proc exit")
}
go f()
go f()
go f()
time.Sleep(2 * time.Second)
testrun = false
time.Sleep(3 * time.Second)
fmt.Println("main proc exit")
go fmt.Println(1)
go fmt.Println(2)
go fmt.Println(3)
fmt.Println("main goroutine finished!")
time.Sleep(1 *time.Second)
}
複製代碼
運行結果:ui
sub proc running ...
sub proc running ...
sub proc running ...
sub proc running ...
sub proc running ...
sub proc running ...
sub proc running ...
sub proc running ...
sub proc running ...
sub proc exit
sub proc exit
sub proc exit
main proc exit
main goroutine finished!
2
1
3
Process finished with exit code 0
複製代碼
完整案例2
package main
import (
"fmt"
"time"
)
// A先被a阻塞,A()結束後關閉b,使b可讀
func A(a,b chan struct{}){
<- a
fmt.Println("A()!")
time.Sleep(1 * time.Second)
close(b)
}
//B首先被a阻塞,B()結束後關閉b,使b可讀
func B(a,b chan struct{}){
<-a
fmt.Println("B()!")
close(b)
}
//C首先被a阻塞
func C(a chan struct{}){
<- a
fmt.Println("C()!")
}
func main(){
x := make(chan struct{})
y := make(chan struct{})
z := make(chan struct{})
fmt.Println("C:z")
go C(z)
fmt.Println("A:x,y")
go A(x,y)
fmt.Println("C:z")
go C(z)
fmt.Println("B: y,z")
go B(y,z)
fmt.Println("C:z")
go C(z)
close(x)
time.Sleep(3 * time.Second)
}
複製代碼
運行結果:spa
C:z
A:x,y
C:z
B: y,z
C:z
A()!
B()!
C()!
C()!
C()!
Process finished with exit code 0
複製代碼
經過兩個案例,能夠看出沒有使用chan,運行是無序的,當使用了chan,運行就變得可控了。code