英文:
Processing odd and even values
问题
我正在学习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)
}
}
请问有什么我可以帮助你的吗?
英文:
I'm learning about channels and concurrency in GO and I'm stuck on a task.
I want to function that passes a slice, filters the numbers and then prints the channel values. The issue is that when I use the channel it deadlocks the program. This is my code:
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)
}
}
答案1
得分: 0
当发送完值后关闭通道:
func processEven(inputs []int) chan int {
evenValues := make(chan int)
var wg sync.WaitGroup
for _, num := range inputs {
wg.Add(1)
go func(num int) {
defer wg.Done()
if num%2 == 0 {
evenValues <- num
}
}(num)
}
go func() {
wg.Wait()
close(evenValues)
}()
return evenValues
}
该代码使用 WaitGroup 来等待发送者完成。
循环接收值直到通道关闭:
func main() {
inputs := []int{1, 17, 34, 56, 2, 8}
evenCh := processEven(inputs)
for num := range evenCh {
fmt.Println(num)
}
}
在通道上使用 range
循环,直到通道关闭。
英文:
Close the channel when done sending values:
func processEven(inputs []int) chan int {
evenValues := make(chan int)
var wg sync.WaitGroup
for _, num := range inputs {
wg.Add(1)
go func(num int) {
defer wg.Done()
if num%2 == 0 {
evenValues <- num
}
}(num)
}
go func() {
wg.Wait()
close(evenValues)
}()
return evenValues
}
The code uses a WaitGroup to wait for the senders to complete.
Loop receiving values until the channel is closed:
func main() {
inputs := []int{1, 17, 34, 56, 2, 8}
evenCh := processEven(inputs)
for num := range evenCh {
fmt.Println(num)
}
}
Range on a channel loops until the channel is closed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论