golang context

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)

}

猜你喜欢

转载自www.cnblogs.com/LC161616/p/10353962.html