context的WithTimeout、WithDeadline、WithCancel

GOOS指的是目标操作系统

GOARCH指的是目标处理器的架构

goland 配置goroot:从官网下载sdk

goland 配置gopath:src的上一级,支持多个,当有多个资源时,go get默认第一个使用

Err方法:返回取消的错误原因,Context被取消原因

Go支持匿名函数,如果我们某个函数只是希望使用一次,可以考虑使用匿名函数,匿名函数也可以实现多次调用

  • WithTimeout
import "time"

// WithTimeout设置超时时间,some函数将ctx传下去,超过设定时间会自动调用cancel
func exec() {
	ctx, cancel:= context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	some(ctx)
}

  • WithDeadline
import "time"

// WithDeadline是设置具体时间点,some函数将ctx传下去,超过设定时间会自动调用cancel
func exec() {
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(500*time.Millisecond))
	defer cancel()
	some(ctx)
}
  • WithCancel
import "time"

// WithCancel是根据具体情况手动调用cancel
func exec() {
	ctx, cancel := context.WithCancel(context.Background())
	deadline = time.Now().Add(500*time.Millisecond)
	if time.Now().After(deadline) {
		cancel()
	}
}

Done方法:返回一个只读的chan,类型为struct{},我们在goroutine中,如果该方法返回的chan可以读取,则意味着context已经发起了取消请求,我们通过Done方法收到这个信号后,就应该做清理操作,然后退出goroutine,释放资源

select就是用来监听和channel有关的IO操作,当 IO 操作发生时,触发相应的动作。

如果连default都没有,则select语句会一直阻塞,直到至少有一个IO操作可以进行

// 创建计时器,1s后触发
timer := time.NewTimer(time.Second)

select {
	// 收到计时器的信号后触发
    case <-timer.C:
          xxx
    case <-ctx.Done():   //当ctx收到取消的信号,执行done操作停止
        timer.Stop()             
}

//对于for select中的break是无法 退出到for循环外,只能goto实现
for {
    select {
        case <-time.After(time.Second * time.Duration(2)):
            break
	}
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值