golang context
Posted lc161616
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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) }
以上是关于golang context的主要内容,如果未能解决你的问题,请参考以下文章