Go中使用Channel等待所有協程結束
阿新 • • 發佈:2019-02-16
讓main方法等待所有協程執行完畢再退出。可能一般思路是設定一個共有變數,然後通過修改這個變數的狀態。這是通過共享變數來通訊的方式,而go要做的是,通過通訊來共享記憶體。
1. 按順序執行
每次通訊進行成對通訊,當main向協程傳送一個寫channel時,同時也等待協程返回一個讀channel。
這兩個channel一定是成對的,所以構造一個結構體
type worker struct { in chan int done chan bool } func chanDemo1(){ var workers [10]worker for i := 0; i < 10; i++ { workers[i] = createWorker1(i) } for i := 0; i < 10; i++ { workers[i].in <- 'a' + i <- workers[i].done } for i := 0; i < 10; i++ { workers[i].in <- 'A' + i <- workers[i].done } } func createWorker1(id int) worker { work := worker{ in: make(chan int), done: make(chan bool), } go func() { for { fmt.Printf("Work %d receiverd %c\n", id, <- work.in) work.done <- true } }() return work } func main(){ chanDemo1() fmt.Println("over") }
- 這個執行結果完全是按照0-9,先小寫再大寫的順序
- 如果這樣順序執行,還要協程幹啥
2. 批量處理
type worker struct { in chan int done chan bool } func chanDemo1(){ var workers [10]worker for i := 0; i < 10; i++ { workers[i] = createWorker1(i) } for i := 0; i < 10; i++ { workers[i].in <- 'a' + i } for _, worker := range workers { <- worker.done } for i := 0; i < 10; i++ { workers[i].in <- 'A' + i } for _, worker := range workers { <- worker.done } } func createWorker1(id int) worker { work := worker{ in: make(chan int), done: make(chan bool), } go func() { for { fmt.Printf("Work %d receiverd %c\n", id, <- work.in) work.done <- true } }() return work }
這樣的話,先列印小寫,再列印大寫,但是大小寫時順序不固定
3. 完全隨機
func chanDemo1(){ var workers [10]worker for i := 0; i < 10; i++ { workers[i] = createWorker1(i) } for i := 0; i < 10; i++ { workers[i].in <- 'a' + i } for i := 0; i < 10; i++ { workers[i].in <- 'A' + i } for _, worker := range workers { <- worker.done <- worker.done } } func createWorker1(id int) worker { work := worker{ in: make(chan int), done: make(chan bool), } go func() { for { fmt.Printf("Work %d receiverd %c\n", id, <- work.in) // 再開一個協程 go func() { work.done <- true}() } }() return work }
這種方式就是完全隨機了
使用channel進行樹的遍歷
func (node *Node) TraverseFunc(f func(*Node)){
if node == nil{
return
}
node.Left.TraverseFunc(f)
f(node)
node.Right.TraverseFunc(f)
}
func (node *Node) TraverseWithChannel() chan *Node{
out := make(chan *Node)
go func() {
node.TraverseFunc(func(node *Node) {
out <- node
})
close(out)
}()
return out
}
func main(){
var root Node
root = Node{Value:3}
root.Left = &Node{}
root.Right = &Node{5,nil,nil}
root.Right.Left = new(Node)
root.Left.Right =&Node{6,nil,nil}
root.Traverse()
c:=root.TraverseWithChannel()
maxNode := 0
for node := range c{
if node.Value > maxNode{
maxNode = node.Value
}
}
fmt.Println("max node value:", maxNode)