在一个goroutine中向通道添加项目,在另一个gorroutine中进行处理



对于围棋和尝试在实践中学习的世界来说,真的是一个新手。我想看看我将如何使用go例程将项目添加到";队列";在一个go例程中,而另一个go例行程序侦听队列并在它们进入时进行处理。在这种情况下,我有一个函数,它将定义数量的项添加到int[]中,而其他函数则尝试在添加时打印它们。。我认为需要发送一个标志来表示一次性例程已停止向队列添加项目。我为noob问题道歉,但我很难理解新的术语和语法。

package main
import "fmt"

func printFromSlice(c chan []int){
i := <-c
// wait for item to be added to channel
fmt.Print(i)
}
func addToSlice (c chan []int, i int)  {
for n := 0; n < i; n++{
c <- n //I know this isnt right
}
// How do we signal this is complete??
}
func main(){
c := make(chan []int)
//add things to []i int
go addToSlice(c, 25)
//do something from []int
go printFromSlice(c)

}

**UPDATE**

修改为使用以下代码,但现在它只会在关闭前对单个打印表单执行~printFromSlice`函数。。。

package main
func printFromSlice(c chan int){
i := <-c
// wait for item to be added to channel
println("read")
println(i)
}
func addToSlice (c chan int)  {
for n := 0; n < 100; n++{
println("add")
println(n)
c <- n
}
close(c)
}
func main(){
println("starting...")
c := make(chan int)
//add things to []i int
go addToSlice(c)
//do something from []int
go printFromSlice(c)
<-c

}

您需要添加一个同步。WaitGroup阻塞主线程,直到两个goroutine可以完成为止。您可以参考此"按示例进行"。

package main
import "sync"
func printFromSlice(c chan int, wg *sync.WaitGroup) {
defer wg.Done() // Decrement the waitgroup counter by 1 after `printFromSlice` returns
// wait for item to be added to channel
// i := <-c // this only waits / blocks 1 time
// For each message arriving at c, read and print
for i := range c { // this would read all messages until channel is closed
println("read")
println(i)
}
}
func addToSlice(c chan int, wg *sync.WaitGroup) {
defer wg.Done() // Decrement the waitgroup counter by 1 after `addToSlice` returns
for n := 0; n < 100; n++ {
println("add")
println(n)
c <- n
}
close(c)
}
func main() {
var wg sync.WaitGroup
println("starting...")
c := make(chan int)
wg.Add(2) // Adds 2 to the waitgroup counter
//add things to []i int
go addToSlice(c, &wg) // Pass the wait group as reference so they can call wg.Done()
//do something from []int
go printFromSlice(c, &wg) // Pass the wait group as reference so they can call wg.Done()
// <-c // No need for this to block the code
wg.Wait() // Waits / blocks until waitgroup counter is 0
}

最新更新