【问题标题】:Writing concurrently with channels与频道同时写入
【发布时间】:2016-09-15 17:25:30
【问题描述】:

我写了一个简短的脚本来同时写一个文件。 一个 goroutine 应该将字符串写入文件,而其他 goroutine 应该通过通道将消息发送给它。 但是,由于某些非常奇怪的原因,创建了文件,但没有通过通道向其中添加任何消息。

package main

import (
    "fmt"
    "os"
    "sync"
)

var wg sync.WaitGroup
var output = make(chan string)

func concurrent(n uint64) {
    output <- fmt.Sprint(n)
    defer wg.Done()
}

func printOutput() {
    f, err :=  os.OpenFile("output.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666);
    if err != nil {
            panic(err)
    }
    defer f.Close()

    for msg := range output {
            f.WriteString(msg+"\n")
    }
}

func main() {
    wg.Add(2)
    go concurrent(1)
    go concurrent(2)
    wg.Wait()
    close(output)
    printOutput()
}

printOutput() goroutine 被完全执行,如果我试图在 for 循环之后写一些东西,它实际上会进入文件。所以这让我认为范围输出可能为空

【问题讨论】:

标签: go concurrency channel


【解决方案1】:

你需要从输出通道中取出一些东西,因为它会阻塞,直到有东西移除你放在它上面的东西。

不是唯一/最好的方法,但是:我将 printOutput() 移到其他函数上方并将其作为 go 例程运行,它可以防止死锁。

package main

import (
    "fmt"
    "os"
    "sync"
)

var wg sync.WaitGroup
var output = make(chan string)

func concurrent(n uint64) {
    output <- fmt.Sprint(n)
    defer wg.Done()
}

func printOutput() {
    f, err := os.OpenFile("output.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
    if err != nil {
        panic(err)
    }
    defer f.Close()

    for msg := range output {
        f.WriteString(msg + "\n")
    }
}

func main() {
    go printOutput()
    wg.Add(2)
    go concurrent(1)
    go concurrent(2)
    wg.Wait()
    close(output)
}

【讨论】:

  • 不正确。您的关闭可能会在 pintOuput 完成之前结束程序。
【解决方案2】:

你得到一个空的output 的原因之一是因为 channels 对于发送/接收都是blocking。

根据您的流程,下面的代码 sn-p 永远不会到达wg.Done(),因为发送通道期望接收端将数据拉出。这是一个典型的死锁例子。

func concurrent(n uint64) {
    output <- fmt.Sprint(n) // go routine is blocked until data in channel is fetched.
    defer wg.Done()
}

让我们来看看 main 函数:

func main() {
    wg.Add(2)
    go concurrent(1)  
    go concurrent(2)
    wg.Wait()       // the main thread will be waiting indefinitely here.
    close(output)   
    printOutput()
}

【讨论】:

  • @Juanvulcano 你在wg.Wait() 之后关闭频道。未达到wg.Done(),因为output &lt;- fmt.Sprint(n) 阻塞等待printOutput() 取消值。而且您永远不会到达 printOutput() ,因为它也在 wg.Wait() 之后。因此,您在wg.Done() 永久等待
【解决方案3】:

我对这个问题的看法:


package main

import (
    "fmt"
    "os"
    "sync"
)

var wg sync.WaitGroup
var output = make(chan string)
var donePrinting = make(chan struct{})

func concurrent(n uint) {
    defer wg.Done() // It only makes sense to defer
     // wg.Done() before you do something.
     // (like sending a string to the output channel)
    output <- fmt.Sprint(n)
}

func printOutput() {
    f, err := os.OpenFile("output.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
    if err != nil {
        panic(err)
    }
    defer f.Close()

    for msg := range output {
        f.WriteString(msg + "\n")
    }
    donePrinting <- struct{}{}
}

func main() {
    wg.Add(2)
    go printOutput()
    go concurrent(1)
    go concurrent(2)
    wg.Wait()
    close(output)
    <-donePrinting
}

每个concurrent 函数将从等待组中扣除。

两个concurrent goroutine 完成后,wg.Wait() 将解除阻塞,并执行下一条指令(close(output))。在关闭通道之前,您必须等待两个 goroutine 完成。相反,如果您尝试以下方法:

go printOutput()
go concurrent(1)
go concurrent(2)
close(output)
wg.Wait()

你可能会在任何一个concurrent goroutines 结束之前执行close(output) 指令。如果通道在并发 goroutine 运行之前关闭,它们将在运行时崩溃(在尝试写入关闭的通道时)。

那么,如果您不等待 printOutput() goroutine 完成,您实际上可以在 printOutput() 有机会完成对其文件的写入之前退出 main()。

因为我想在退出程序之前等待printOutput() goroutine 完成,所以我还创建了一个单独的通道来表示printOutput() 已完成。

&lt;-donePrinting 指令阻塞,直到main 通过donePrinting 通道接收到一些东西。 一旦main 收到任何东西(甚至是printOutput() 发送的空结构),它就会解除阻塞并运行到结论。

https://play.golang.org/p/nXJoYLI758m

【讨论】:

  • 应该是这样的play.golang.org/p/Z1UTnLXwICV
  • 错过了一个丢失的 wg.Done 通话.......play.golang.org/p/4GshqCcd32m
  • 从 printOutput() 中修复(删除)了一个额外的 wg.Done()。
  • 是的,我在发布之前没有充分阅读和测试我的代码。见play.golang.org/p/tqDK4kHbyfQ
  • @mh-cbon 您提交的第二个解决方案:1. 不在操场上执行,2. 并发函数中的 wg WaitGroup 没有定义,3. 实际上很聪明。第三种解决方案很棒
猜你喜欢
  • 2016-02-03
  • 2015-10-28
  • 1970-01-01
  • 2020-01-30
  • 2016-12-01
  • 1970-01-01
  • 2012-10-04
  • 2018-09-16
  • 1970-01-01
相关资源
最近更新 更多