美文网首页
关于golang的context控制协程的例子

关于golang的context控制协程的例子

作者: llicety | 来源:发表于2018-09-13 17:49 被阅读0次

关于context的概念,可以参考http://www.flysnow.org/2017/05/12/go-in-action-go-context.html
协程间的通信方式
1.共享变量(需要注意资源竞争,一般用互斥锁)
2.chan
3.context
以下是context的代码例子

package main

import (
    "sync"
    "fmt"
    "time"
    "context"
    "math/rand"
)

func test1(wg * sync.WaitGroup, ctx context.Context, cfunc context.CancelFunc){
    defer wg.Done()
    fmt.Println("test1 run")
    d := time.Duration(rand.Intn(10))
    fmt.Printf("%d 秒之后,test1 将终止\n", d)
    time.AfterFunc( d * time.Second, cfunc)
    for{
        select {
        case <-ctx.Done():
            fmt.Println("test1 return")
            return
        default:
            fmt.Println("default")
            time.Sleep(1 * time.Second)

        }
    }
}

func test2(wg *sync.WaitGroup, ctx context.Context, cfunc context.CancelFunc){
    defer wg.Done()
    fmt.Println("test2 run")
    d := time.Duration(rand.Intn(10))
    fmt.Printf("%d 秒之后,test2 将终止\n", d)
    time.AfterFunc( d * time.Second, cfunc)
    for {
        select {
        case <-ctx.Done():
            fmt.Println("test2 return")
            // 这里要不用return 要不就用break + lebal, 不能直接用break,只用break,这里只跳出case
            return
        default:
            fmt.Println("test2 default")
            time.Sleep(1 * time.Second)
        }
    }
}

func main() {
    wg := sync.WaitGroup{}
    rand.Seed(time.Now().UnixNano())
    ctx, cancel := context.WithCancel(context.Background())
    wg.Add(2)
    timeStart := time.Now().Unix()
    go test1(&wg, ctx, cancel)
    go test2(&wg, ctx, cancel)
    wg.Wait()
    timeEnd := time.Now().Unix()
    fmt.Printf("运行时长为:%d s\n", timeEnd - timeStart)
    fmt.Println("主协成退出!")
}

相关文章

  • 关于golang的context控制协程的例子

    关于context的概念,可以参考http://www.flysnow.org/2017/05/12/go-in-...

  • golang中最大协程数的限制(线程)

    golang中最大协程数的限制 golang中有最大协程数的限制吗?如果有的话,是通过什么参数控制呢?还是通过每个...

  • golang学习

    1:goroutine内存可能存在泄露,可能用context控制 2:开启协程,占用内存,协程开启你用过多,过多会...

  • 浅谈GoLang协程

    GoLang协程 学习golang也有一段时间了,这里讲一下自己对golang协程的使用理解,golang很多人都...

  • go 并发协程管理 - 使用 Context 和通道做协程管理

    Go 语言提供了 Context 标准库是为了解决复杂的并发场景下,对协程有更好的控制。Context 的作用和它...

  • Go

    数据结构 chan channel是golang进程内协程间通讯的管道 例子 输出: 性质 从chan读,如果ch...

  • golang

    golang携程调度,runtime包 golang内存模型 csp原理 context的原理 slice底层结构...

  • golang控制协程(grouting)数量

    方法一:使用带有缓冲的channel 的特性 直到缓冲区被填满后,写端才会阻塞。 缓冲区被读空,读端才会阻塞。 代...

  • go 中 限制 goroutine 数量以及使用协程池

    需要使用协程池? Golang 开发需要协程池吗[https://www.zhihu.com/question/3...

  • Golang:协程

    协程(Goroutine)是与其他函数或方法同时运行的函数或方法。可以认为它是轻量级的线程。与线程相比,创建 Go...

网友评论

      本文标题:关于golang的context控制协程的例子

      本文链接:https://www.haomeiwen.com/subject/inhggftx.html