【问题标题】:Use channel to limit the number of active go routines使用 channel 限制活动 goroutine 的数量
【发布时间】:2019-05-27 11:54:30
【问题描述】:

我正在阅读“Go 编程语言” 限制运行的 go 例程数量的一种方法是使用“计数信号量”。

另一种方式是Limiting number of go routines running

在这个案例中,我允许另外 2 个 go 例程。我遇到死锁错误。 是什么导致我的代码出现死锁?

package main

import (
    "bytes"
    //"context"
    "fmt"
    "runtime"
    "strconv"
    "sync"
    "time"
)

func main() {
    max := 2
    var wg sync.WaitGroup
    squares := make(chan int)
    tokens := make(chan struct{}, max)
    for i := 20; i >= 1; i-- {
        tokens <- struct{}{}
        wg.Add(1)
        go func(n int) {
            defer func() { <-tokens }()
            defer wg.Done()
            fmt.Println("run go routine ", getGID())
            squares <- Square(n)

        }(i)
    }

    go func() {
        wg.Wait()
        close(squares)
    }()

    for s := range squares {
        fmt.Println("Get square: ", s)

    }
}

func Square(num int) int {
    time.Sleep(time.Second * time.Duration(num))
    fmt.Println(num * num)
    return num * num
}

func getGID() uint64 {
    b := make([]byte, 64)
    b = b[:runtime.Stack(b, false)]
    b = bytes.TrimPrefix(b, []byte("goroutine "))
    b = b[:bytes.IndexByte(b, ' ')]
    n, _ := strconv.ParseUint(string(b), 10, 64)
    return n
}

【问题讨论】:

    标签: go


    【解决方案1】:

    goroutines 阻止发送到squares。 Main 没有在 squares 上接收,因为它阻止启动 goroutine。

    通过将启动 goroutine 的代码移动到 goroutine 来修复。这允许 main 继续执行到 squares 上的接收。

    squares := make(chan int)
    go func() {
        max := 2
        var wg sync.WaitGroup
        tokens := make(chan struct{}, max)
        for i := 20; i >= 1; i-- {
            tokens <- struct{}{}
            wg.Add(1)
            go func(n int) {
                defer func() { <-tokens }()
                defer wg.Done()
                fmt.Println("run go routine ", getGID())
                squares <- Square(n)
    
            }(i)
        }
    
        wg.Wait()
        close(squares)
    }()
    
    fmt.Println("About to receive")
    for s := range squares {
        fmt.Println("Get square: ", s)
    
    }
    

    Run it on the playground.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-30
      • 2017-09-25
      • 2021-10-07
      • 2020-12-25
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多