码迷,mamicode.com
首页 > 其他好文 > 详细

golang context

时间:2019-02-06 19:53:33      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:def   class   sele   fun   import   print   inf   com   return   

 

 

 

package main

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

var (
	cxt            context.Context
	cxt1           context.Context
	cancelFunction context.CancelFunc
)

func gooo(ctx context.Context,num int){
	for{
		select{
		case <-ctx.Done() :
			fmt.Println("退出操作",num)
			return
		default:
			fmt.Println("默认操作.........",num)
			time.Sleep(time.Second*2)
		}
	}
}


func main() {
	cxt = context.Background()
	cxt, cancelFunction = context.WithCancel(cxt)

	cxt1,cancelFunct := context.WithCancel(cxt)


	go gooo(cxt, 1)
	go gooo(cxt1,2)

	// cancelFunction = cancelFunction
	time.Sleep(time.Second*10)
	cancelFunct()
	time.Sleep(time.Second * 10)
	cancelFunction()
	fmt.Println("exited....")

}

 

技术图片

 

 

 

package main

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

var (
	cxt            context.Context
	cxt1           context.Context
	cancelFunction context.CancelFunc
)

func gooo(ctx context.Context,num int){
	for{
		select{
		case <-ctx.Done() :
			fmt.Println("退出操作",num)
			return
		default:
			fmt.Println("默认操作.........",num)
			time.Sleep(time.Second*2)
		}
	}
}


func main() {
	cxt = context.Background()
	cxt, cancelFunction = context.WithCancel(cxt)

	cxt1,_ := context.WithCancel(cxt)


	go gooo(cxt, 1)
	go gooo(cxt1,2)

	// cancelFunction = cancelFunction

	time.Sleep(time.Second * 10)
	cancelFunction()
	fmt.Println("exited....")

	time.Sleep(time.Second*300)

}

技术图片

 

golang context

标签:def   class   sele   fun   import   print   inf   com   return   

原文地址:https://www.cnblogs.com/LC161616/p/10353962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!