首页 > 其他分享 >context sample in golang

context sample in golang

时间:2023-05-10 11:26:00浏览次数:31  
标签:golang 调用 int sync sample context time

package main

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

func routine(id int, ctx context.Context, msg chan int, wg *sync.WaitGroup) {

    defer wg.Done()

    fmt.Println("routine ", id)

    ticker := time.NewTicker(1 * time.Second)

    for range ticker.C {
        select {
        case <-ctx.Done():
            fmt.Println(ctx.Err(), id)
            return
        default:
            fmt.Println("recv msg ", id, <-msg)
        }
    }
}

func main() {
    var wg sync.WaitGroup

    msg := make(chan int, 10)

    //send msg
    for i := 0; i < 10; i++ {
        msg <- i
    }

    //ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Second))
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    //ctx, cancel := context.WithCancel(context.Background())

    defer cancel()

    for i := 1; i < 3; i++ {
        wg.Add(1)
        go routine(i, ctx, msg, &wg)
    }

    defer close(msg)

    //time.Sleep(3 * time.Second)
    //cancel()

    wg.Wait()

    fmt.Println("main exit")
}

    调用context 的WithCancel 方法时,需要主动调用cancel, 才能发送 Done,从而结束每个协程,而WithDeadline (WithTimeout 是对WithDeadline的封装) 因为有时间参数,不需要主动调用cancel.

标签:golang,调用,int,sync,sample,context,time
From: https://www.cnblogs.com/wallywl/p/17387390.html

相关文章

  • spring框架_ApplicationContext实现
    ApplicationContext实现ApplicationContext有四个经典实现ClassPathXmlApplicationContext:经典容器,基于classpath下xml格式的配置文件来创建FileSystemXmlApplicationContext:基于磁盘路径下xml格式的配置文件前两种实现都是用来帮助beanfactory读取bean的都是读取XML......
  • golang获得基础硬件信息
    packageutilsimport("runtime""time""github.com/shirou/gopsutil/v3/cpu""github.com/shirou/gopsutil/v3/disk""github.com/shirou/gopsutil/v3/mem")const(B=1KB=1024*BMB=1024*......
  • golang的zap日志切割
    packageinternalimport("github.com/flipped-aurora/gin-vue-admin/server/global"rotatelogs"github.com/lestrrat-go/file-rotatelogs""go.uber.org/zap/zapcore""os""path""time")varF......
  • spring框架_Applicationcontext功能
    Applicationcontext的功能拓展主要来自于不属于beanfactory的接口,主要包括四个接口Messagesource:国际化ResourcePatternResolver:获取资源ApplicationEventPublisher:发布事件EnvironmentCapable:获取环境变量感觉发布事件这个功能有点像消息队列,发布订阅,在compent......
  • golang中xorm自动维护表结构自动导入数据的实现
    Xorm简介Go标准库提供的数据库接口database/sql比较底层,使用它来操作数据库非常繁琐,而且容易出错。因而社区开源了不少第三方库,有各式各样的ORM(ObjectRelationalMapping,对象关系映射库),如gorm和xorm。其中xorm是一个简单但强大的ORM库,使用它可以大大简化我们的数据库操作,笔......
  • Golang GMP原理(2)
    GMP调度场景场景1P拥有G1,M1获取P后开始运行G1,G1使用gofunc创建G2,为了局部性G2优先加入到P1的本地队列场景2G1运行完成后(函数:goexit),M上运行的goroutine切换为G0,G0负责调度时协程的切换(函数:schedule)。从P的本地队列取G2,从G0切换到G2,并开始运行G2(函数:execute)。实现了线程......
  • C# 窗体控件ContextMenuStrip下拉项之间的分割线
    1.效果如图: 2.选中ContextMenuStrip控件,在Items属性中添加Separator 3. (其中第3,4步,通过上下箭头,摆置好你要分割的位置)原文链接......
  • Golang MySQL 操作
    1.  创建go_db目录      mkdirgo_db2. root@VirtualBox:/mnt/share/goframe/go_db#gomodinitgo_dbgo:creatingnewgo.mod:modulego_dbroot@VirtualBox:/mnt/share/goframe/go_db#goget-ugithub.com/go-sql-driver/mysqlgo:addedgithub.com/go-......
  • golang map key struct hash policy
     Theeasiestandmostflexiblewayistousea struct asthekeytype,includingallthedatayouwanttobepartofthekey,soinyourcase:typeKeystruct{X,Yint}Andthat'sall.Usingit:m:=map[Key]int{}m[Key{2,2}]=4m[Key{2......
  • 学习Golang时遇到的似懂非懂的概念
    背景......