在一个 goroutine 中将项目添加到通道并在另一个 goroutine 中处理

Add items to channel in one goroutine and process in another

围棋世界的新手,尝试边做边学。我想看看如何使用 go 例程在一个 go 例程中将项目添加到“队列”,而另一个 go 例程侦听队列并在它们进入时处理事物。在这种情况下,我有一个 func,它将定义数量的项目添加到 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 to block the main thread until the two goroutine could finish. You could refer to this 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
}