代码示例:
package main import ( "fmt" "time" "golang.org/x/net/context" ) func main() { // ctx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(time.Second*5)) ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*5) ctx = context.WithValue(ctx, "Test", "123456") // defer cancelFunc() if t, ok := ctx.Deadline(); ok { fmt.Println(time.Now()) fmt.Println(t.String()) } go func(ctx context.Context) { fmt.Println(ctx.Value("Test")) for { select { case <-ctx.Done(): fmt.Println(ctx.Err()) return // default: // continue } } }(ctx) // if ctx.Err() == nil { // fmt.Println("Sleep 10 seconds...") // time.Sleep(time.Second * 10) // } // if ctx.Err() != nil { // fmt.Println("Alredy exit...") // } time.Sleep(time.Second * 3) cancelFunc() // for { // if ctx.Err() != nil { // fmt.Println("gracefully exit...") // break // } // } }
go程序包源码解读——golang.org/x/net/context:
http://m.blog.csdn.net/article/details?id=49100433
Go语言并发模型:像Unix Pipe那样使用channel:
https://segmentfault.com/a/1190000006261218
http://www.dotcoo.com/golang-channel-is-closed
如何安全关闭channel:
http://www.golangtc.com/t/53d8a5e1320b5252650000f0
channel小技巧: http://www.jb51.net/article/68909.htm
使用Golang的Context管理上下文: http://blog.csdn.net/u014029783/article/details/53782864
Go语言并发模型:使用 context: https://segmentfault.com/a/1190000006744213
golang x/net/context包笔记: http://blog.csdn.net/sryan/article/details/51969129
golang-context使用方式: http://www.tuicool.com/articles/ENnyYvR
Golang 1.7.3 Context 简单用法.类似sync.WaitGroup: http://blog.csdn.net/fyxichen/article/details/52104549
golang中context包解读: http://www.tuicool.com/articles/n6rInyn
Go语言并发模型:使用 context: http://www.tuicool.com/articles/3ieeuay