golang中channel

1. Channel是Go中的一个核心类型,你可以把它看成一个管道,通过它并发核心单元就可以发送或者接收数据进行通讯(communication)。

 2. select

package main

import (
	"fmt"
	"time"
)

func fibonacci(c, quit chan int) {
	x, y := 0, 1
	for {
		select {
		case c <- x:  // 负责往通道写数据
			x, y = y, x + y
			time.Sleep(time.Millisecond * 200)
		case <-quit:  // 负责从通道读数据
			fmt.Println("quite")
			return
		}
	}
}

func main() {
	c := make(chan int)
	quit := make(chan int)
	go func() {  // 此goroutine负责从通道c中读取数据,读取10个数据后,往通道quit中写入数据
		for i := 0; i < 10; i++ {
			fmt.Println(<-c)
		}
		quit <- 0
	}()
	fibonacci(c, quit)
}

3. select 的超时处理

package main

import (
	"fmt"
	"time"
)

func main() {
	var c = make(chan string, 1)
	go func() {
		time.Sleep(time.Second * 2)
		c <- "result1"
	}()
	select {
	case ret := <-c:
		fmt.Println(ret)
	case <-time.After(time.Second * 2):  // select的超时处理
		fmt.Println("time outer")
	}
}

  

posted @ 2021-10-13 17:20  专职  阅读(37)  评论(0编辑  收藏  举报