gpt4 book ai didi

concurrency - Go 中的并发生产者和消费者

转载 作者:IT王子 更新时间:2023-10-29 01:55:53 25 4
gpt4 key购买 nike

我想在 Go 中创建一个带有管理程序的生产者/消费者。例如:我有一个 5 个生产者、5 个消费者和一个管理者。生产者有他们自己的本地数组,他们遍历它们并将元素发送给管理器。消费者拥有他们自己的本地数组,其中包含元素消费的信息;他们也将它们发送给经理。管理器拥有自己的数组,它存储元素的内容和数量(例如 - 如果生产者发送 1 1 2 3 1 2 0 元素,管理器数组看起来像 1 3 2 1(一个 0、三个 1、两个 2 和一个 3),它处理生产者和消费者的请求——将一个元素放入数组(生产)或删除它(消费)。

是否可以用 Go 编写这样的程序?我已经在 J​​AVA + CSP 中完成了此操作,其中包含用于发送信息的 channel 和管理器中的守卫,以确定当生产者和消费者尝试处理相同元素时应首先执行哪个过程(例如,生产者想要将 1 添加到管理器数组同时消费者想要消费 1)。

欢迎提供任何示例或建议,因为我找不到任何关于我想做什么的信息。如果需要我可以提供我的 JAVA+CSP 代码。

更新。同步如何(不是从空数组中获取)?例如 - 如果消费者想要消费管理器数组中尚不存在的元素(例如消费者想要消费'3',但经理没有任何一个)但是生产者有这个元素并且它将在几次之后生产迭代 - 我怎样才能让消费者一次又一次地检查管理器数组,直到生产者工作完成?我是否需要为消费者元素创建结构(或类)并标记它们是否被使用,或者 Go 有特定的方法来执行此操作?

最佳答案

这是一个完整的示例,包括 channel 清理。在所有消费者和生产者完成后,管理器打印出结果(我使用了 map 而不是 slice ,因为我认为这使代码更简单)。

package main

import "fmt"

// Consume processes the numbers in ns, sending them on ch after they're
// processed. When the routine is finished, it signals that on done.
func Consume(done chan bool, ch chan int, ns []int) {
for i := range ns {
ch <- i
}
done <- true
}

// Produce "creates" the numbers in ns, sending them on ch after they're
// produced. When the routine is finished, it signals that on done.
func Produce(done chan bool, ch chan int, ns []int) {
for i := range ns {
ch <- i
}
done <- true
}

// Manage creates consumers and producers for the given int slices.
// It returns once all consumers and producers are finished.
func Manage(cons, pros [][]int) {
cch := make(chan int)
pch := make(chan int)
dch := make(chan bool)
n := len(cons) + len(pros)
data := make(map[int]int)
for _, c := range cons {
go Consume(dch, cch, c)
}
for _, p := range pros {
go Produce(dch, pch, p)
}
for n > 0 {
select {
case c := <-cch:
data[c] -= 1
case c := <-pch:
data[c] += 1
case <-dch:
n -= 1
}
}
close(cch)
close(pch)
close(dch)
fmt.Println(data)
}
func main() {
cons := [][]int{{1, 3, 5}, {0, 1, 5}}
pros := [][]int{{0, 1, 1}, {3, 5, 5, 7}}
Manage(cons, pros)
}

关于concurrency - Go 中的并发生产者和消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20744619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com