登录
首页 >  Golang >  Go问答

能否向Go通道添加元素?

来源:stackoverflow

时间:2024-03-14 10:42:25 207浏览 收藏

golang学习网今天将给大家带来《能否向Go通道添加元素?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在尝试找到一种使用 goroutine 递归地完成 go 中的任务的方法。该程序的目标是将输入元素放入通道并添加到输出通道输入 -1 直到达到 0。加工工人数量应具有适应性。我遵循的过程如下:

创建输入和输出通道。将起始编号添加到输入通道。初始化工作人员以运行工作人员功能。循环并打印输出通道中的输出。

func main() {
    inputchannel := make(chan int, 1)
    outputchannel := make(chan int)
    inputchannel <- 100
    numworkers := 4
    for i := 0; i < numworkers; i++ {
        go worker(inputchannel, outputchannel)
    }
    for elem := range outputchannel {
        fmt.println("output: ", elem)
    }
}

接下来,在 order 函数中,我们循环遍历输入通道中的元素,每次检查是否有更多元素要接收。如果还有更多元素要接收,我们打印输入元素,从该元素中减去 1,然后发送到输入通道,以便另一个工作人员在该元素大于 0 时拾取。如果输入通道中没有剩余任何内容,那么我们返回。

func worker(input chan int, output chan<- int) {
    defer close(input)
    defer close(output)
    for {
        element, more := <-input
        if more {
            fmt.println("input: ", element)
            element--
            if element != 0 {
                input <- element
            }
        } else {
            fmt.println("all jobs processed")
            return
        }
    }
}

我看到的输出是:

Input:  100
Input:  99
Input:  98
Input:  97
Input:  96
Input:  95
Input:  94
Input:  93
Input:  92
Input:  91
Input:  90
Input:  89
Input:  88
Input:  87
Input:  86
Input:  85
Input:  84
Input:  83
Input:  82
Input:  81
Input:  80
Input:  79
Input:  78
Input:  77
Input:  76
Input:  75
Input:  74
Input:  73
Input:  72
Input:  71
Input:  70
Input:  69
Input:  68
Input:  67
Input:  66
Input:  65
Input:  64
Input:  63
Input:  62
Input:  61
Input:  60
Input:  59
Input:  58
Input:  57
Input:  56
Input:  55
Input:  54
Input:  53
Input:  52
Input:  51
Input:  50
Input:  49
Input:  48
Input:  47
Input:  46
Input:  45
Input:  44
Input:  43
Input:  42
Input:  41
Input:  40
Input:  39
Input:  38
Input:  37
Input:  36
Input:  35
Input:  34
Input:  33
Input:  32
Input:  31
Input:  30
Input:  29
Input:  28
Input:  27
Input:  26
Input:  25
Input:  24
Input:  23
Input:  22
Input:  21
Input:  20
Input:  19
Input:  18
Input:  17
Input:  16
Input:  15
Input:  14
Input:  13
Input:  12
Input:  11
Input:  10
Input:  9
Input:  8
Input:  7
Input:  6
Input:  5
Input:  4
Input:  3
Input:  2
Input:  1
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:31 +0x179

goroutine 6 [chan receive]:
main.worker(0xc00004e070, 0xc00005c060)
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:9 +0xac
created by main.main
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:29 +0xc4

goroutine 7 [chan receive]:
main.worker(0xc00004e070, 0xc00005c060)
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:9 +0xac
created by main.main
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:29 +0xc4

goroutine 8 [chan receive]:
main.worker(0xc00004e070, 0xc00005c060)
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:9 +0xac
created by main.main
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:29 +0xc4

goroutine 9 [chan receive]:
main.worker(0xc00004e070, 0xc00005c060)
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:9 +0xac
created by main.main
        /Users/ianmitchell/go/src/github.com/iancmitchell/channel-recursion/main.go:29 +0xc4
exit status 2

我已经尝试了多种方式,依赖于这样的通道并使用等待组,但我似乎无法让该过程完成所有项目并发出输出。


解决方案


好的,我们开始吧。首先,请注意您的代码中存在一些问题。然后修复它们。

  • 正如 Adrian 所说,从已关闭或没有元素的通道中读取。在你的工作函数中,你正在这样做。当您在另一个工作人员关闭输入通道后从输入通道读取元素时,就会发生这种情况。

    func worker(input chan int, output chan<- int) {
        defer close(input)
        ...
        for {
            element, more := <-input
            ...
        }
    }
    

    那么,为什么在所有工作人员完成后不关闭输入通道呢?

  • 解决输入通道的问题后,当您尝试从输出通道读取时,会出现另一个问题。此外,您没有在输出通道上发送任何内容。如果您不需要该渠道,那么为什么要使用这个渠道。而且这个输出通道是无缓冲的(大小为0的通道和发送接收应该同时进行,否则会出现死锁情况)。请参阅 herehere 中的缓冲与非缓冲。也许网络上有更多有用的文档。感谢我的朋友 Nightfury1204 在他的 this post 上提供了第一个关于缓冲通道与非缓冲通道的链接。

    outputchannel := make(chan int) // unbuffered, no size is defined
    ...
    for elem := range outputchannel {
        fmt.println("output: ", elem)
    }
    

    因此,如果您想将某些内容发送到输出通道,那么逻辑就是您自己的。例如,您可以在工作人员中完成输入通道处理后发送一些内容。在这种情况下,请将您的输出通道声明为长度为 4 的缓冲通道(因为您正在运行 4 个工作进程)。完成所有工作人员后,关闭输出通道,然后读取。

    outputchannel := make(chan int, 4) // buffered
    ...
    // after finishing all your workers
    close(outputchannel)
    for elem := range outputchannel {
        fmt.println("output: ", elem)
    }
    

请注意,使用 "sync" 包中的 sync.WaitGroup 来等待 要完成的 goroutine 集合。

参见下面的示例: https://play.golang.org/p/WAqwyR0ggNN

import "fmt"
import "sync"

func main() {
    inputChannel := make(chan int, 1)
    outputChannel := make(chan int, 4)

    var wg sync.WaitGroup
    wg.Add(4)

    inputChannel <- 100
    numWorkers := 4
    for i := 0; i < numWorkers; i++ {
        go func() {
            defer wg.Done()
            for {
                select {
                case element := <-inputChannel:
                    fmt.Println("Input: ", element)
                    element--
                    if element != 0 {
                        inputChannel <- element
                    }
                default:
                    outputChannel<-0
                    fmt.Println("All Jobs Processed", len(outputChannel))
                    return
                }
            }
        }()
    }
    wg.Wait()
    close(inputChannel)
    close(outputChannel)
    for elem := range outputChannel {
        fmt.Println("Output: ", elem)
    }
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>