码迷,mamicode.com
首页 > 其他好文 > 详细

Go并发控制--context的使用

时间:2018-06-19 14:02:31      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:ext   dea   package   执行   put   select   any   fun   cancel   

并发控制 Cancel Example

通过使用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...

并发超时控制 Timeout Example

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...

Go并发控制--context的使用

标签:ext   dea   package   执行   put   select   any   fun   cancel   

原文地址:https://www.cnblogs.com/lanyangsh/p/9197753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!