真正的围棋世界,尝试边干边学。我想看看如何使用go例程在一个go例程中将项目添加到“队列”中,而另一个go例程监听队列并在它们进入时对其进行处理。在这种情况下,我有一个函数,可以在int []中添加定义数量的项,而其他尝试在添加时打印它们。.我假设将需要发送一个标志来发出信号,表明一个go例程已停止添加队列中的项目。我为菜鸟问题表示歉意,但正在努力理解新的术语和语法。
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
}
最佳答案
您需要添加sync.WaitGroup来阻塞主线程,直到两个goroutine完成。您可以引用此Go by Example。
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
}
关于go - 在一个goroutine中将项目添加到 channel ,在另一个goroutine中进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64530568/