funcmain() { var c1, c2, c3 chanint var i1, i2 int select { case i1 = <-c1: fmt.Printf("received ", i1, " from c1\n") case c2 <- i2: fmt.Printf("sent ", i2, " to c2\n") case i3, ok := (<-c3): // same as: i3, ok := <-c3 if ok { fmt.Printf("received ", i3, " from c3\n") } else { fmt.Printf("c3 is closed\n") } default: fmt.Printf("no communication\n") } }
1 2 3 4 5 6 7 8 9 10 11
select { //不停的在这里检测 case <-chanl : //检测有没有数据可以读 //如果chanl成功读取到数据,则进行该case处理语句 case chan2 <- 1 : //检测有没有可以写 //如果成功向chan2写入数据,则进行该case处理语句
//比如在下面的场景中,使用全局resChan来接受response,如果时间超过3S,resChan中还没有数据返回,则第二条case将执行 var resChan = make(chanint) // do request functest() { select { case data := <-resChan: doData(data) case <-time.After(time.Second * 3): fmt.Println("request time out") } }
退出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//主线程(协程)中如下: var shouldQuit=make(chanstruct{}) fun main(){ { //loop } //...out of the loop select { case <-c.shouldQuit: cleanUp() return default: } //... }
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !