学习goroutine
goroutine
goroutine 协程,可以看成一个轻量级的线程。与线程相比,协程的调度方是自己,而线程则是操作系统。go 中select 一直监视着IO变化
package main
import (
"fmt"
"time"
)
func Producer (queue chan<- int){
for i:=0;i<100;i++{
queue <- i
}
}
func Consumer( queue <-chan int){
for {
v := <- queue
fmt.Println("receive:", v)
}
}
func main(){
queue := make(chan int)
go Producer(queue)
time.Sleep(1e9)
go Consumer(queue)
go Consumer(queue)
go Consumer(queue)
go Consumer(queue)
time.Sleep(1e9) //让Producer与Consumer完成
}
等价二叉树
package main
import "golang.org/x/tour/tree"
import "fmt"
type Tree struct {
Left *Tree
Value int
Right *Tree
}
// Walk 步进 tree t 将所有的值从 tree 发送到 channel ch。
func Walk(t *tree.Tree, ch chan int){
if t.Left !=nil{
Walk(t.Left,ch)
}
ch<-t.Value
if t.Right !=nil{
Walk(t.Right,ch)
}
}
// Same 检测树 t1 和 t2 是否含有相同的值。
func Same(t1, t2 *tree.Tree) bool{
var ret bool
ch1 :=make(chan int,10)
ch2 :=make(chan int,10)
go Walk(t1,ch1)
go Walk(t2,ch2)
for i:=0;i<10;i++{
if <-ch1 != <-ch2{
ret= false
break
}else{
ret= true
}
}
return ret
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(2)))
}