我正在尝试使用Go中的并发性和渠道。我面临的问题主要是并发性,因此,我并没有放弃以下逻辑错误或应更改的逻辑。
我有一个缓冲通道,其缓冲大小为“ N”,它还表示将要创建的goroutine的数量。所有例程都从一个通道读取并在另一个通道中写入,而主要的goroutine将从最后一个通道中打印值。
1个输入通道--- N个goroutines查找并添加到输入和输出--- 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的所有数字并完成。谢谢
牧羊人nacy
相关分类