处理奇数和偶数

我正在学习 GO 中的通道和并发性,但我被困在一项任务中。我想要传递一个切片、过滤数字然后打印通道值的函数。问题是,当我使用频道时,它会使程序陷入僵局。这是我的代码:


package main


import (

    "fmt"

)


func processOdd(inputs []int) chan int {

    oddValues := make(chan int)

    for _, numbers := range inputs {

        go func(num int) {

            if num%2 != 0 {

                oddValues <- num

            }

        }(numbers)

    }

    return oddValues

}


func processEven(inputs []int) chan int {

    evenValues := make(chan int)

    for _, numbers := range inputs {

        go func(num int) {

            if num%2 == 0 {

                evenValues <- num

            }

        }(numbers)

    }

    return evenValues

}


func main() {

    inputs := []int{1, 17, 34, 56, 2, 8}

    evenCH := processEven(inputs)

    for range inputs {

        fmt.Print(<-evenCH)

    }

}


斯蒂芬大帝
浏览 111回答 1
1回答

HUH函数

完成发送值后关闭通道:func processEven(inputs []int) chan int {&nbsp; &nbsp; evenValues := make(chan int)&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; for _, num := range inputs {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go func(num int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if num%2 == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; evenValues <- num&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }(num)&nbsp; &nbsp; }&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; &nbsp; &nbsp; close(evenValues)&nbsp; &nbsp; }()&nbsp; &nbsp; return evenValues}该代码使用WaitGroup来等待发送者完成。循环接收值直到通道关闭:func main() {&nbsp; &nbsp; inputs := []int{1, 17, 34, 56, 2, 8}&nbsp; &nbsp; evenCh := processEven(inputs)&nbsp; &nbsp; for num := range evenCh {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(num)&nbsp; &nbsp; }}通道上的范围循环,直到通道关闭。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go