教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Golang中WaitGroup、Context、goroutine定时器及超时学习笔记

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

发布时间:2023-03-12   编辑:jiaochengji.com
教程集为您提供Golang中WaitGroup、Context、goroutine定时器及超时学习笔记等资源,欢迎您收藏本站,我们将为您提供最新的Golang中WaitGroup、Context、goroutine定时器及超时学习笔记资源

原文连接:http://targetliu.com/2017/5/2...
好久没有发过文章了 - -||,今天发一篇 golanggoroutine 相关的学习笔记吧,以示例为主。

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
到此这篇关于“Golang中WaitGroup、Context、goroutine定时器及超时学习笔记”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang goroutine 通知_深入golang之---goroutine并发控制与通信
字节跳动的 Go 语言面试会问哪些问题?
golang WaitGroup源码解析
Golang-context
理解 golang 中的 context(上下文) 包
[Go学习] 并发控制之WaitGroup计数信号量
golang 面试题(从基础到高级)
golang 深入浅出之 goroutine 理解
Goroutine并发调度模型深度解析&amp;手撸一个协程池
Go WaitGroup实现原理

[关闭]
~ ~