Golang中WaitGroup、Context、goroutine定时器及超时学习笔记

WaitGroup

WaitGroupsync 包中,用于阻塞主线程执行直到添加的 goroutine 全部执行完毕。

Context

Context 是在 Go1.7 中移入标准库的。

Context 包不仅实现了在程序单元之间共享状态变量的方法,同时能通过简单的方法,使我们在被调用程序单元的外部,通过设置ctx变量值,将过期或撤销这些信号传递给被调用的程序单元。

goroutine的定时器及超时

这是两个有趣又实用的功能,在标准库 time 包里提供。

示例

源码

<!--more-->

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func main() {
    ch := make(chan int)
    //定义一个WaitGroup,阻塞主线程执行
    var wg sync.WaitGroup
    //添加一个goroutine等待
    wg.Add(1)
    //goroutine超时
    go func() {
        //执行完成,减少一个goroutine等待
        defer wg.Done()
        for {
            select {
            case i := <-ch:
                fmt.Println(i)
            //goroutine内部3秒超时
            case <-time.After(3 * time.Second):
                fmt.Println("goroutine1 timed out")
                return
            }
        }
    }()
    ch <- 1
    //新增一个1秒执行一次的计时器
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()
    //新增一个10秒超时的上下文
    background := context.Background()
    ctx, _ := context.WithTimeout(background, 10*time.Second)
    //添加一个goroutine等待
    wg.Add(1)
    go func(ctx context.Context) {
        //执行完成,减少一个goroutine等待
        defer wg.Done()
        for {
            select {
            //每秒一次
            case <-ticker.C:
                fmt.Println("tick")
            //内部超时,不会被执行
            case <-time.After(5 * time.Second):
                fmt.Println("goroutine2 timed out")
            //上下文传递超时信息,结束goroutine
            case <-ctx.Done():
                fmt.Println("goroutine2 done")
                return
            }
        }
    }(ctx)
    //等待所有goroutine执行完成
    wg.Wait()
}

执行结果

1
tick
tick
tick
goroutine1 timed out
tick
tick
tick
tick
tick
tick
tick
goroutine2 done

来源: segmentfault

作者: Target_Liu

文章来自互联网如果对个人或单位有侵犯其著作权行为,请您联系我们:lk_qmail@foxmail.com

在线交流