golang context学习记录2
上篇文章中,我们已经学习了使用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的更多相关文章
- golang context学习记录1
1.前言 一个请求,可能涉及多个API调用,多个goroutine,如何在多个API 之间,以及多个goroutine之间协作和传递信息,就是一个问题. 比如一个网络请求Request,需要开启一些g ...
- golang "%p"学习记录随笔
对于获取slice的指针地址, 通过unsafe.Pointer 和 "%p"占位符两种方式得到的地址是不同的 s := make([]int, 1) t.Log(unsafe.P ...
- 【golang学习记录】环境搭建
[golang学习记录]环境搭建 一. 概述 本文是[golang学习记录]系列文章的第一篇,安装Go语言及搭建Go语言开发环境,接下来将详细记录自己学习 go 语言的过程,一方面是为了巩固自己学到的 ...
- Golang Context 的原理与实战
本文让我们一起来学习 golang Context 的使用和标准库中的Context的实现. golang context 包 一开始只是 Google 内部使用的一个 Golang 包,在 Gola ...
- Quartz 学习记录1
原因 公司有一些批量定时任务可能需要在夜间执行,用的是quartz和spring batch两个框架.quartz是个定时任务框架,spring batch是个批处理框架. 虽然我自己的小玩意儿平时不 ...
- Spring学习记录(九)---通过工厂方法配置bean
1. 使用静态工厂方法创建Bean,用到一个工厂类 例子:一个Car类,有brand和price属性. package com.guigu.spring.factory; public class C ...
- 【转】BLE 学习记录
原文网址:http://m.blog.csdn.net/blog/chiooo/43985401 BLE 学习记录 ANROID BLE 开发,基于 bluetoothlegatt 分析 mBluet ...
- 我的Spring学习记录(二)
本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...
- 我的Spring学习记录(四)
虽然Spring管理这我们的Bean很方便,但是,我们需要使用xml配置大量的Bean信息,告诉Spring我们要干嘛,这还是挺烦的,毕竟当我们的Bean随之增多的话,xml的各种配置会让人很头疼. ...
随机推荐
- symfony3 yml配置文件详解
AppBundle\Entity\BlogComment: //映射实体 type: entity //类型 repositoryClass: AppBundle\Repository ...
- MyBatis--把SQL带进Java
简单来看软件服务的工作流程:用户端界面操作请求<---->本地处理|远程服务程序拦截转发请求<---->服务端逻辑功能实现<--MyBatis用在这里-->数据库. ...
- 第一篇、Python入门
一 编程与编程语言 python是一门编程语言,作为学习python的开始,需要事先搞明白:编程的目的是什么?什么是编程语言?什么是编程? 编程的目的: #计算机的发明,是为了用机器取代/解放人力,而 ...
- KVM和Docker的对比
虚拟化技术对比: KVM:全虚拟化,需要模拟各种硬件 docker:严格来说不算是虚拟化技术,只是进程隔离和资源限制 实例启动进程对比: 在kvm虚拟机中执行top命令,看宿主机进程树,根本看不到to ...
- 自学Python6.5-内置模块(re、collections )
自学Python之路-Python基础+模块+面向对象自学Python之路-Python网络编程自学Python之路-Python并发编程+数据库+前端自学Python之路-django 自学Pyth ...
- springboot集成dubbo服务报错No provider available for the service
检查了下发现是因为没有正确编写暴露服务的注解,需要注意下: @Service(interfaceClass = StudentService.) @Component public class Stu ...
- 【每日一包0003】kind-of
github地址:https://github.com/ABCDdouyae... kind-of 判断数据类型用法:kind-of(date)返回:string 数据类型 January undef ...
- sublime添加书签
ctrl+f2添加书签, f2切换书签
- ssm框架使用详解&配置两个数据源
学习ssm框架已经快一年了,今天把这个框架总结一下. SSM 就是指 spring.SpringMVC和Mybatis.先说一下基本概念(百度上搜的) 1.基本概念 1.1.Spring Spring ...
- es6的Map结构
es6的Map结构主要解决Object的键名只能是单一属性的问题.它可以是字符串,对象,数组,等等 其中有个问题要注意一下,就是 var map = new Map(); map.set(['a'], ...