上篇文章中,我们已经学习了使用context实现控制多个goroutine的退出。

本文将继续介绍如何使用context实现超时情况下,让多个goroutine退出。

例子

首先,启动3个goroutine,分别为1,2,3。这3个goroutine又分别启动一个goroutine。

一共有6个goroutine,它们之间关系如下:

  • 1

    • 11
  • 2
    • 21
  • 3
    • 31

task1,2,3被限制在指定时间内结束,即50ms。

如果不能按时结束,会触发超时操作,这样,task 1、2、3接收到超时信号,取消自己启动的goroutine(即task11,21,31),然后退出。

最后,所有的goroutine都退出了。

代码如下:

ackage main

import (
"context"
"fmt"
"time"
) func PrintTask(ctx context.Context, taskName string) { for { select { case <- ctx.Done():
fmt.Println("task:", taskName, "ctx error:", ctx.Err()," then task exit...")
return
default:
time.Sleep(1*time.Second)
fmt.Println("task:", taskName, " doing something...")
} } } func mainTask(ctx context.Context, taskName string) { ctx1, cancel := context.WithCancel(ctx)
defer cancel() // create a new task
newTaskName := taskName + "1"
go PrintTask(ctx1, newTaskName) for { select { case <- ctx.Done():
fmt.Println("task:", taskName, "ctx error:", ctx.Err()," then task exit...")
return
default:
time.Sleep(1*time.Second)
fmt.Println("task:", taskName, " doing something...")
} } } func main() { ctx := context.Background()
timeout := 50*time.Millisecond
ctx, _ = context.WithTimeout(ctx, timeout) go mainTask(ctx, "1")
go mainTask(ctx, "2")
go mainTask(ctx, "3") select{
case <-ctx.Done():
// timeout
fmt.Println("main task error:", ctx.Err())
} fmt.Println("main exit...")
time.Sleep(3*time.Second)
}

输出

main task error: context deadline exceeded
main exit...
task: 21 doing something...
task: 1 doing something...
task: 21 ctx error: context deadline exceeded then task exit...
task: 3 doing something...
task: 3 ctx error: context deadline exceeded then task exit...
task: 1 ctx error: context deadline exceeded then task exit...
task: 11 doing something...
task: 11 ctx error: context deadline exceeded then task exit...
task: 31 doing something...
task: 2 doing something...
task: 31 ctx error: context deadline exceeded then task exit...
task: 2 ctx error: context deadline exceeded then task exit...

golang context学习记录2的更多相关文章

  1. golang context学习记录1

    1.前言 一个请求,可能涉及多个API调用,多个goroutine,如何在多个API 之间,以及多个goroutine之间协作和传递信息,就是一个问题. 比如一个网络请求Request,需要开启一些g ...

  2. golang "%p"学习记录随笔

    对于获取slice的指针地址, 通过unsafe.Pointer 和 "%p"占位符两种方式得到的地址是不同的 s := make([]int, 1) t.Log(unsafe.P ...

  3. 【golang学习记录】环境搭建

    [golang学习记录]环境搭建 一. 概述 本文是[golang学习记录]系列文章的第一篇,安装Go语言及搭建Go语言开发环境,接下来将详细记录自己学习 go 语言的过程,一方面是为了巩固自己学到的 ...

  4. Golang Context 的原理与实战

    本文让我们一起来学习 golang Context 的使用和标准库中的Context的实现. golang context 包 一开始只是 Google 内部使用的一个 Golang 包,在 Gola ...

  5. Quartz 学习记录1

    原因 公司有一些批量定时任务可能需要在夜间执行,用的是quartz和spring batch两个框架.quartz是个定时任务框架,spring batch是个批处理框架. 虽然我自己的小玩意儿平时不 ...

  6. Spring学习记录(九)---通过工厂方法配置bean

    1. 使用静态工厂方法创建Bean,用到一个工厂类 例子:一个Car类,有brand和price属性. package com.guigu.spring.factory; public class C ...

  7. 【转】BLE 学习记录

    原文网址:http://m.blog.csdn.net/blog/chiooo/43985401 BLE 学习记录 ANROID BLE 开发,基于 bluetoothlegatt 分析 mBluet ...

  8. 我的Spring学习记录(二)

    本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...

  9. 我的Spring学习记录(四)

    虽然Spring管理这我们的Bean很方便,但是,我们需要使用xml配置大量的Bean信息,告诉Spring我们要干嘛,这还是挺烦的,毕竟当我们的Bean随之增多的话,xml的各种配置会让人很头疼. ...

随机推荐

  1. 目标 - 在虚拟机CentOS7中无图形界面安装Oracle11G R2版本

    参考: https://www.cnblogs.com/yejingcn/p/10278473.html centos7启动oracle su - oracle //切换到自己的oracle账户 ls ...

  2. 用python编写一个合格的ftp程序,思路是怎样的?

      经验1.一般在比较正规的类中的构造函数.都会有一个verify_args函数,用于验证传入参数.尤其是对于系统传参.2.并且系统传参,其实后面大概都是一个函数名 例如:python server. ...

  3. 标准C语言(11)

    多文件编程时一个文件里可以包含多个函数,一个函数只能属于一个文件 /* * 多文件编程演示 * */ #include <stdio.h> #include "01add.h&q ...

  4. (转)AIX中修改主机名 要注意

    smit hostname改名后一个常见的问题是:hostname看到的是新名, uname -n 看到的仍是旧名.没见IBM针对改名有官方的步骤,因此共享下我多年来的一直使用的方法.  1.smit ...

  5. MHA监控进程异常退出(MHA版本:0.56)

    最近遇到一个非常诡异的问题,mha后台进程自己中断退出了.以下是报错:Mon Dec 21 20:16:07 2015 - [info] OK.Mon Dec 21 20:16:07 2015 - [ ...

  6. Web前端经典面试试题(一)

    本篇收录了一些面试中经常会遇到的经典面试题,并且都给出了我在网上收集的答案.眼看新的一年马上就要开始了,相信很多的前端开发者会有一些跳槽的悸动,通过对本篇知识的整理以及经验的总结,希望能帮到更多的前端 ...

  7. DevExpress ASP.NET Bootstrap v19.1版本亮点:Scheduler控件

    行业领先的.NET界面控件DevExpress 正式发布了v19.1版本,本文将以系列文章的方式为大家介绍DevExpress ASP.NET Bootstrap Controls中Rich Text ...

  8. oracle 数据库安装及jdbc的连接

    今天,我在oracle的官网下载了数据库并进行安装,其中遇到一些问题,在此进行记录. 1.下载,之后,按照网上的教程进行安装,开始遇到 下载之后出现11g 出现ins13001环境不满足最低要求 这个 ...

  9. 动软生成器 Liger model生成模板

    <#@ template language="c#" HostSpecific="True" #> <#@ output extension= ...

  10. JZOJ5373【NOIP2017提高A组模拟9.17】信仰是为了虚无之人

    题目 分析 我们发现,如果[l,r]的异或和为k是真要求,有且仅当不存在[l,i]和[i,r]两个区间的异或和不为k. 我们用带权并查集了维护这些,但是,由于区间不连续,我们将点权移到边上,对于区间[ ...