登录
首页 >  Golang >  Go问答

Go 提供了类似于 Threadpool 的功能吗?

来源:stackoverflow

时间:2024-02-23 18:33:25 276浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《Go 提供了类似于 Threadpool 的功能吗?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我来自 Java/Scala,最近开始使用 Go。在 Java/Scala 中,线程池非常常见,它们的使用至少有 4 个不同的原因。

  1. 重用已实例化的工作线程
  2. 资源管理。当我们有多个线程池时,我们可以确保如果系统的某一部分出现突发情况,也不会阻止其他部分的运行。
  3. 自定义我们想要的调度类型(分叉/合并、经典、预定等...)
  4. 自定义拒绝政策。

由于 Goroutines 非常轻,所以不需要 1,尽管提供一个会很好,但我们可以创建某种工作池,而无需太多麻烦来解决 2。

但是,我觉得在Go中我们无法解决34

是因为不需要它还是只是缺少功能?


解决方案


正如你所猜测的,由于 (1) 在 go 中基本上不是问题,所以线程/工作池的需要要少得多。 (2) 也可以通过速率限制和资源信号量等技术来解决。至于 (3),go 运行时执行 goroutine 调度,因此自定义它并不容易,也不符合惯用语。

也就是说,线程/工作线程池在 go 中非常容易实现。这是 gobyexample 中的一个简单示例:

// In this example we'll look at how to implement
// a _worker pool_ using goroutines and channels.

package main

import "fmt"
import "time"

// Here's the worker, of which we'll run several
// concurrent instances. These workers will receive
// work on the `jobs` channel and send the corresponding
// results on `results`. We'll sleep a second per job to
// simulate an expensive task.
func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "started  job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {

    // In order to use our pool of workers we need to send
    // them work and collect their results. We make 2
    // channels for this.
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    // This starts up 3 workers, initially blocked
    // because there are no jobs yet.
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    // Here we send 5 `jobs` and then `close` that
    // channel to indicate that's all the work we have.
    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    // Finally we collect all the results of the work.
    // This also ensures that the worker goroutines have
    // finished. An alternative way to wait for multiple
    // goroutines is to use a [WaitGroup](waitgroups).
    for a := 1; a <= 5; a++ {
        <-results
    }
}

如果你用谷歌搜索一下,你会发现一堆实现这种模式用于各种用途的第 3 方包。正如您可能猜到的那样,没有单一的最佳方法可以做到这一点,因此您将选择对您的特定用例重要的任何方法。

以上就是《Go 提供了类似于 Threadpool 的功能吗?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>