【发布时间】:2019-01-13 20:39:39
【问题描述】:
我正在尝试在 Go 中使用并发和通道。我现在面临的问题主要是并发的思想,所以我不排斥下面的逻辑是错误的或者应该改的。
我有一个缓冲通道,它的缓冲区大小为“N”,它还表示将要创建的 goroutine 的数量。所有的例程都从一个通道读取并写入另一个通道,主 goroutine 将打印来自最终通道的值。
1 个输入通道 --- N 个 goroutine 查找并添加到输入和输出 --- 1 个输出通道
问题是我总是遇到死锁,因为我不知道如何关闭一个正在喂食的通道,也不知道它什么时候会停止,所以我也无法关闭输出通道。
代码如下:
package main
const count = 3
const finalNumber = 100
// There will be N routines running and reading from the one read channel
// The finalNumber is not known, in this examples is 100, but in the main problem will keep self feeding until the operation gives a wrong output
// readingRoutine will feed read channel and the print channel
func readingRoutine(read, print chan int) {
for i := range read {
print <- i
if i < finalNumber && i+count < finalNumber {
read <- i + count
}
}
}
// This is the main routine that will be printing the values from the print channel
func printingRoutine(print chan int) {
for i := range print {
println(i)
}
}
func main() {
read := make(chan int, count)
print := make(chan int, count)
// Feed count numbers into the buffered channel
for i := 0; i < count; i++ {
read <- i
}
// count go routines will be processing the read channel
for i := 0; i < count; i++ {
go readingRoutine(read, print)
}
printingRoutine(print)
}
在这个例子中,它应该打印从 0 到 100 的所有数字并完成。 谢谢
【问题讨论】:
标签: multithreading go concurrency channel goroutine