Workspace
  • Introduction
  • Algorithm
    • 二叉树
    • 排序算法
  • Basic Knowledge
    • CAP定理
    • CAS-SSO-单点登陆
    • 单向认证-双向认证
  • CICD
  • Cloud Native
  • Docker
    • Docker特性
    • Docker资源隔离
  • Golang
    • Standard Library
      • Archive
        • Builtin
        • Zip
    • Golang-container包
    • Golang-fallthrough关键字
    • Golang For Slect
    • Golang-Goroutine泄露
    • Golang Interface
    • Golang-json.Unmarshal
    • Golang Label
    • Golang Map String Struct
    • Golang Map To Struct
    • Golang Override Package Function
    • Golang-Slice删除元素
    • Golang Switch
    • Golang-sync.Cond
    • Golang-sync.Map
    • Golang-sync.once
    • Golang-type关键字
    • Golang-代码生成
    • golang-并发数控制
    • Golang-并发退出
    • Golang-插件系统
    • Golang-继承
    • Golang之channel
    • Golang之continue
    • Golang之make与new和nil
    • Golang之map
    • Golang之reflect
    • Golang之类型判断
    • Golang代码质量检测
    • Golang变量避坑
    • Golang字符串遍历
    • golang并发控制代码示例
    • Golang性能优化
    • Golang死锁
    • goroutine-协程-线程-进程
    • go值传递
    • go内存逃逸分析
    • go并发MGP模式
    • go并发控制
    • 垃圾回收-三色法
  • Istio
    • 服务网格
  • Jenkins
    • Jenkin On K 8 S
    • Jenkins Mac
  • Kubernetes
    • Deployment
    • k8s容器内查看-cpu-memory分配情况
    • kube-proxy原理
    • Kubernetes Informers
    • Kubernetes扩展点
    • Kubernetes部署策略
    • Pod Non Root
    • Pod驱逐
    • PV PVC Storage Class
    • Security Context
    • 优雅热更新
  • Python
    • Python-vs-Golang协程区别
  • Serviceless
  • Shell
    • Shell小技巧
  • VPN
    • OC Serv
  • Redis
Powered by GitBook
On this page
  • WaitGroup
  • Chan 通知
  • Context
  • 参考链接

Was this helpful?

  1. Golang

golang并发控制代码示例

WaitGroup

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    wg.Add(2)
    go func() {
        time.Sleep(2 * time.Second)
        fmt.Println("1号完成")
        wg.Done()
    }()
    go func() {
        time.Sleep(2 * time.Second)
        fmt.Println("2号完成")
        wg.Done()
    }()
    wg.Wait()
    fmt.Println("好了,大家都干完了,放工")
}

Chan 通知

package main

import (
    "fmt"
    "time"
)

func main() {
    stop := make(chan bool)

    go func() {
        for {
            select {
            case <-stop:
                fmt.Println("监控退出,停止了...")
                return
            default:
                fmt.Println("goroutine监控中...")
                time.Sleep(2 * time.Second)
            }
        }
    }()

    time.Sleep(10 * time.Second)
    fmt.Println("可以了,通知监控停止")
    stop<- true
    //为了检测监控过是否停止,如果没有监控输出,就表示停止了
    time.Sleep(5 * time.Second)

}

Context

Context 接口

type Context interface {
    Deadline() (deadline time.Time, ok bool)

    Done() <-chan struct{}

    Err() error

    Value(key interface{}) interface{}
}

Context的继承衍生

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithValue(parent Context, key, val interface{}) Context
  • 控制一个 goroutine

package main

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

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go func(ctx context.Context) {
        for {
            select {
            case <-ctx.Done():
                fmt.Println("监控退出了,停止了 ...")
                return
            default:
                fmt.Println("goroutine监控中 ...")
                time.Sleep(2 * time.Second)
            }
        }
    }(ctx)
    time.Sleep(10 * time.Second)
    fmt.Println("可以了通知监控停止")
    cancel()
    time.Sleep(5 * time.Second)
}
  • 控制多个 goroutine

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

func main() {

    ctx, cancelFunc := context.WithCancel(context.Background())
    go watch(ctx, "监控1: ")
    go watch(ctx, "监控2: ")
    go watch(ctx, "监控3: ")
    time.Sleep(10 * time.Second)
    fmt.Println("可以了,通知监控停止 ...")
    cancelFunc()
    time.Sleep(5 * time.Second)

}

func watch(ctx context.Context, name string) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println(name, "监控退出,停止了 ...")
            return
        default:
            fmt.Println(name, "goroutine 监控中 ...")
            time.Sleep(2 * time.Second)
        }
    }
}
  • WithValue 传递元数据

package main

import (
    "context"
    "fmt"
    "time"
)
var key string = "name"

func main() {
    ctx, cancelFunc := context.WithCancel(context.Background())
    valueCtx1 := context.WithValue(ctx, key, "监控1: ")
    go watch(valueCtx1)
    valueCtx2 := context.WithValue(ctx, key, "监控2: ")
    go watch(valueCtx2)
    valueCtx3 := context.WithValue(ctx, key, "监控3: ")
    go watch(valueCtx3)
    time.Sleep(10 * time.Second)
    fmt.Println("可以了,通知监控停止 ...")
    cancelFunc()
    time.Sleep(5 * time.Second)

}

func watch(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println(ctx.Value(key), "监控退出,停止了 ...")
            return
        default:
            fmt.Println(ctx.Value(key), "goroutine 监控中 ...")
            time.Sleep(2 * time.Second)
        }
    }
}

参考链接

PreviousGolang字符串遍历NextGolang性能优化

Last updated 4 years ago

Was this helpful?

Go语言实战笔记(二十)| Go Context