有7种重要的channel模式需要理解,因为channel实现了Goroutine之间的通信。

等待结果模式

这是channel的基本使用模式,创建一个goroutine来执行一些任务,然后将执行结果通过channel通知到对应的其他Goroutine。

func WaitForResult() {
    ch := make(chan string)
    go func() {
        time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
        ch <- "data"
        fmt.Println("child : sent signal")
    }()
    d := <-ch
    fmt.Println("parent : recv'd signal :", d)
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

这里使用不带缓存的channel来接收数据,可以保证子goroutine发送的数据立刻被接收到。

扇出/扇入模式

这种模式是包含多个Goroutine向channel发送数据,要保证数据都能接收到。

func FanOut() {
    children := 2000
    ch := make(chan string, children)
    for c := 0; c < children; c++ {
        go func(child int) {
            time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)
            ch <- "data"
            fmt.Println("child : sent signal :", child)
        }(c)
    }
    for children > 0 {
        d := <-ch
        children--
        fmt.Println(d)
        fmt.Println("parent : recv'd signal :", children)
    }
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

这里我们创建了2000个goroutine来执行任务,为了保证Goroutine不会相互影响,采用带缓存的channel来接收执行结果。主goroutine使用for循环来接收channel里面的数据。sleep模拟执行的任务。

等待任务模式

这种模式是子goroutine通过channel接收来自主goroutine发送的数据,也可以是执行任务的函数。

func WaitForTask() {
    ch := make(chan string)
    go func() {
        d := <-ch
        fmt.Println("child : recv'd signal :", d)
    }()
    time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
    ch <- "data"
    fmt.Println("parent : sent signal")
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

这里也是使用不带缓存的channel,子goroutine等待channel发送数据,接收并执行任务。

Goroutine池

该模式还使用了等待任务模式,允许根据资源情况限制子goroutine的个数。

func pooling() {
    ch := make(chan string)
    g := runtime.GOMAXPROCS(0)
    for c := 0; c < g; c++ {
        go func(child int) {
            for d := range ch {
                fmt.Printf("child %d : recv'd signal : %s\n", child, d)
            }
            fmt.Printf("child %d : recv'd shutdown signal\n", child)
        }(c)
}
    const work = 100
    for w := 0; w < work; w++ {
        ch <- "data"
        fmt.Println("parent : sent signal :", w)
    }
    close(ch)
    fmt.Println("parent : sent shutdown signal")
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

这里我们创建了一组Goroutine来接收同一个channel发送来的数据。这里高效的原因是多个goroutine可以并行执行,注意不是并发。

首先创建一个不带缓冲的通道。使用无缓冲的通道是至关重要的,因为如果没有信号级别的保证,就不能在发送时执行超时和取消。代码的下一部分决定池将包含的子Goroutines的数量。

g := runtime.GOMAXPROCS(0)

该函数可以读取机器cpu核数,也就是能并行执行代码的cpu核数。如果参数大于0,直接返回的是并发个数。
使用for-range读取channel中的数据可以节省代码,当然也可以使用以下代码来读取channel数据:

for c := 0; c < g; c++ {
    go func( child int) {
        for {
            d, wd := <-ch     <-- CHANGED
            if !wd {          <-- CHANGED
            break.            <-- CHANGED
           }
            fmt.Printf("child %d : recv'd signal : %s\n", child, d)
        }
        fmt.Printf("child %d : recv'd shutdown signal\n", child)
    }(c)
}

Drop模式

该模式在写入channel的数据量比较大的时候,超出缓冲的容量就选择丢弃数据。例如当应用程序负载太大就可以丢弃一些请求。

func Drop() {
    const cap = 100
    ch := make(chan string, cap)
    go func() {
        for p := range ch {
            fmt.Println("child : recv'd signal :", p)
        }
    }()
    const work = 2000
    for w := 0; w < work; w++ {
        select {
        case ch <- "data":
            fmt.Println("parent : sent signal :", w)
        default:
            fmt.Println("parent : dropped data :", w)
        }
    }
    close(ch)
    fmt.Println("parent : sent shutdown signal")
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

我们创建一个带缓存的channel和一个Goroutine来接收任务。在缓冲区被填满之前,Goroutine无法及时处理所有的工作。表示服务已满负荷运行。

在for循环里面使用select,是一个受阻塞的模块,每个case代表一个channel操作,发送或接收。但是,这个select也使用了default关键字,它将select转换为非阻塞调用。关键就在这里,如果channel缓冲区满了,select就会执行default。在web服务里面,我们可以在default中返回500内部错误,或者将请求存起来。

取消模式

取消模式用于在执行一些IO操作的时候,可以选择超时时间。你可以选择取消操作,或者直接退出。

func Cancellation() {
    duration := 150 * time.Millisecond
    ctx, cancel := context.WithTimeout(context.Background(), duration)
    defer cancel()
    ch := make(chan string, 1)
    go func() {
        time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)
        ch <- "data"
    }()
    select {
    case d := <-ch:
        fmt.Println("work complete", d)
    case <-ctx.Done():
        fmt.Println("work cancelled")
    }
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

这里使用context创建超时上下文实例ctx,主Goroutine在select中通过ctx.Done读取是否超时。这里使用defer调用cancel()防止内存溢出。

在主goroutine中select等待ch通道数据或者超时,哪个先完成就执行哪个case。

带信号量的扇入/扇出

这种模式可以随时控制可执行的Goroutine数量。

func FanOutSem() {
    children := 2000
    ch := make(chan string, children)
    g := runtime.GOMAXPROCS(0)
    sem := make(chan bool, g)
    for c := 0; c < children; c++ {
        go func(child int) {
            sem <- true
            {
                t := time.Duration(rand.Intn(200)) * time.Millisecond
                time.Sleep(t)
                ch <- "data"
                fmt.Println("child : sent signal :", child)
            }
            <-sem
        }(c)
    }
    for children > 0 {
        d := <-ch
        children--
        fmt.Println(d)
        fmt.Println("parent : recv'd signal :", children)
    }
    time.Sleep(time.Second)
    fmt.Println("-------------------------------------------------")
}

这里一开始创建了一个缓冲为2000的channel。和前面的扇入/扇出没啥区别。另一个chennel sem也被创建了,在每个子goroutine内部使用,可以控制子Goroutine是否能够写入数据容量,缓冲区满的话子goroutine就会阻塞。后面的for循环还是用于等待每个goroutine执行完成。

重试超时模式

这种模式在网络服务中很实用,例如在连接数据库的时候,发起ping操作可能会失败,但是并不希望马上退出,而是在一定时间内发起重试。

func RetryTimeout(ctx context.Context, retryInterval time.Duration,
    check func(ctx context.Context) error) {
    for {
        fmt.Println("perform user check call")
        if err := check(ctx); err == nil {
            fmt.Println("work finished successfully")
            return
        }
        fmt.Println("check if timeout has expired")
        if ctx.Err() != nil {
            fmt.Println("time expired 1 :", ctx.Err())
            return
        }
        fmt.Printf("wait %s before trying again\n", retryInterval)
        t := time.NewTimer(retryInterval)
        select {
        case <-ctx.Done():
            fmt.Println("timed expired 2 :", ctx.Err())
            t.Stop()
            return
        case <-t.C:
            fmt.Println("retry again")
        }
    }
}

这里函数接收一个context指定超时时间,每次重试时间间隔,以及重试函数check,由函数调用者定义。

该函数的核心是for无限循环,在循环内先检查check函数是否执行完成,接着在select中判断是否超时,以及定义重试计时器。

channel取消模式

可以创建一个单独的channel用来实现取消的功能。

func channelCancellation(stop <-chan struct{}) {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    go func() {
        select {
        case <-stop:
            cancel()
        case <-ctx.Done():
        }
    }()

    func(ctx context.Context) error {
        req, err := http.NewRequestWithContext(
            ctx,
            http.MethodGet,
            "https://www.ardanlabs.com/blog/index.xml",
            nil,
        )
        if err != nil {
            return err
        }
        _, err = http.DefaultClient.Do(req)
        if err != nil {
            return err
        }
        return nil
    }(ctx)
}

该函数的关键在于创建一个新的goroutine并使用select来等待两个channel发送的数据。第一个channel是一个空结构体类型,另一个是context。在接收到stop通道值时,就调用cancel函数,取消所有接收了对应context函数的执行。

转自:https://www.jianshu.com/p/a1310e0b6757