Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Golang中WaitGroup、Context、goroutine定时器及超时学习笔记大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

WaitGroup

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

Context

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

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

大佬总结

以上是大佬教程为你收集整理的Golang中WaitGroup、Context、goroutine定时器及超时学习笔记全部内容,希望文章能够帮你解决Golang中WaitGroup、Context、goroutine定时器及超时学习笔记所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: