1.定义2个管道两个协程,一个协程写数据,一个协程读取数据。主线程。实施监控读取完成 代码如下
package main import ( "fmt" ) func WriteData(wchan chan int){ for i:=0; i<50;i++{ wchan<-i; //time.Sleep(time.Second*2); fmt.Printf("wirte chan is %v ",i); } close(wchan);//关闭管道 } func ReadData(wchan chan int, exichan chan bool){ for { v,ok:= <-wchan; if !ok { break; } //time.Sleep(time.Second*2);//读管道 fmt.Printf("read channle is %v ",v); } exichan <- true; close(exichan); } func main() { wchan:=make(chan int,50); exitchan:=make(chan bool,1); go WriteData(wchan); go ReadData(wchan,exitchan); for {//使用for循环阻塞 bol,_:= <- exitchan; if bol { break; } } fmt.Printf("master process is end "); }
2.使用3个协程完成sum求和问题
package main import ( "fmt" ) func WChan(wchan chan int){ for i:=0;i<2000;i++ { wchan <- i; //fmt.Printf("write data is %v ",i); } close(wchan); } func ReadChan(wchan chan int,signelChan chan bool,mapchan chan map[interface{}]interface{}){ for { num,ok:= <- wchan; if !ok { break; } //fmt.Printf("read data is %v ",num); sum:=0; for j:=0;j<=num;j++ { sum=sum+j; } tmpMap:=make(map[interface{}]interface{}); tmpMap[num]=sum; mapchan <- tmpMap;//写入map管道 //fmt.Printf("num的数字为%vsum求和为%v ",num,sum); } signelChan <-true; close(signelChan); } func reeadMap(mapChan chan map[interface{}]interface{}){ for { tmpMap,ok:= <-mapChan; if !ok { break; } for k,v:=range tmpMap { fmt.Printf("key=%v value=%v ",k,v); } } } func main(){ writechan:=make(chan int ,2000);//写管道 bolChan:=make(chan bool);//信号量管道 mapchan:=make(chan map[interface{}]interface{}); go WChan(writechan); go ReadChan(writechan,bolChan,mapchan); go reeadMap(mapchan); for { bol,_:= <-bolChan; if !bol { break; } } }