天天看點

【GoLang】golang context channel 詳解

代碼示例:

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

 golang判斷短chan channel是否關閉: 

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