通过使用WithCancel可以取消一个或多个goroutine的执行,以实现对并发的控制。
package main 
import (
    "context"
    "fmt"
    "time"
)
func PrintTask(ctx context.Context) {
    for {
    
        select {
        
        case <- ctx.Done():
            return
        default:
            time.Sleep(2*time.Second)
            fmt.Println("A man must walk down many roads.")
        }
    
    }
}
func main() {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    
    defer cancel()
    go PrintTask(ctx)
    go PrintTask(ctx)
    go PrintTask(ctx)
    time.Sleep(3*time.Second)
    fmt.Println("main exit...")
}
WithCancel返回cancel函数,调用cancel函数会关闭Done channel,PrintTask就会结束。
output
A man must walk down many roads.
A man must walk down many roads.
A man must walk down many roads.
main exit...
WithTimeout可以实现并发超时控制,使goroutine执行超时时自动结束。
package main 
import (
    "context"
    "fmt"
    "time"
)
func main() {
    ctx := context.Background()
    timeout := 50*time.Millisecond
    ctx, cancel := context.WithTimeout(ctx, timeout)
    
    defer cancel()
    done := make(chan int,1)
    go func() {
        // do something
        time.Sleep(1*time.Second)
        done<- 1
    }()
    select{
    case <-done:
        fmt.Println("work done on time")
    case <-ctx.Done():
        // timeout
        fmt.Println(ctx.Err())
    }
    fmt.Println("main exit...")
}
output:
context deadline exceeded
main exit...
原文:https://www.cnblogs.com/lanyangsh/p/9197753.html