Context上下文包套路入门(1) context包被称为上下文包go 1.7加入用于协程之间的上下文数据的传递、中止核控制超时。在网络编程中可用于请求的中止比如服务访问链的中止a用户注册-b调用用户服务-c调用积分服务。其中a调用bb调用c。如果由于a和b之间因为某些原因被取消或者超时了那么b和c之间也要取消。Context接口源码解读typeContextinterface{//返回一个超时时间Deadline()(deadline time.Time,okbool)//返回只读channel//一旦可读代表父context发起取消操作通过该方法可以收到此信号//完成协程退出并返回Err()Done()-chanstruct{}//返回context被取消的原因Err()error//获取Context上绑定值根据key线程安全Value(keyinterface{})interface{}}空上下文在进行上下文控制之前首先要创建一个顶层context。go内置包提供了一个方法context.Background()WithTimeout超时自动取消当执行一个go协程时超时自动取消协程packagemainimport(contextfmttime)// 模拟一个最小执行时间的阻塞函数funcincr(aint)int{res:a1time.Sleep(time.Second*1)returnres}// 提供一个阻塞接口// 计算ab注意a,b不能是负数// 如果计算被中断则返回-1funcAdd(ctx context.Context,a,bint)int{fmt.Printf(开始)res:0fori:0;ia;i{resincr(res)select{case-ctx.Done()://父context超时了return-1}}fori:0;ib;i{resincr(res)select{case-ctx.Done()://父context超时了return-1}}returnres}funcmain(){ctx,_:context.WithTimeout(context.Background(),time.Second*2)res:Add(ctx,1,2)fmt.Println(res)//-1}WithCancel 手动取消方法funcmain(){ctx,cancel:context.WithCancel(context.Background())gofunc(){time.Sleep(time.Second*2)cancel()//在调用处主动取消}()res:Add(ctx,1,2)fmt.Println(res)//-1}