3.1 go context代码示例

context.WithCancel
返回两个有关联的对象,ctx与cancel,调用cancel发送一个空struct给ctx,ctx一旦接收到该对象后,就终止goroutine的执行;
ctx是线程安全的,可以同时传递给多个goroutine,触发cancel时,取消所有goroutine的执行
package main

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

func testContext(){
    ctx,cancel := context.WithCancel(context.Background())
    go d1(ctx)
    go d2(ctx)
    
    time.Sleep(7*time.Second)
    cancel()
}

func d1(ctx context.Context){
    i:=0
    for {
        time.Sleep(1*time.Second)
        i++
        select {
            case <- ctx.Done():
                fmt.Println("d1 over")
                return
                
            default:
                fmt.Println("d1 ",i)
        }
    }
}

func d2(ctx context.Context){

    fmt.Println("d2 start")
    <- ctx.Done()
    fmt.Println("d2 over")
}

func main(){
    testContext()
    fmt.Println("main over")
}

输出

d2 start
d1  1
d1  2
d1  3
d1  4
d1  5
d1  6
main over

猜你喜欢

转载自www.cnblogs.com/perfei/p/11529122.html
3.1