登录
首页 >  Golang >  Go问答

如何从通道中读取数据一旦我的 GoRoutines 运行完毕?

来源:stackoverflow

时间:2024-02-15 12:36:23 338浏览 收藏

大家好,今天本人给大家带来文章《如何从通道中读取数据一旦我的 GoRoutines 运行完毕?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我目前有两个函数pushnodes(node)和updatenodes(node)。在 pushnodes 函数中,我通过通道推送要在 updatenodes 中使用的值。为了保存准确的通道值,我需要在启动 updatenodes() 之前完成所有 pushnodes go 例程。 goroutines 执行完毕后如何仍然访问通道值?

我不断收到“致命错误:所有 goroutine 都在睡觉 - 死锁!”。请让我知道如何从频道获取这些值。有更好/替代的方法吗?

//pushNodes is a function that will push the nodes values
   func pushNodes(node Node) {
      defer wg.Done()
      fmt.Printf("Pushing: %d \n", node.number)
      //Choose a random peer node
      var randomnode int = rand.Intn(totalnodes)
      for randomnode == node.number {
        rand.Seed(time.Now().UnixNano())
        randomnode = rand.Intn(totalnodes)
      }
      //If the current node is infected, send values through the channel
      if node.infected {
         sentchanneldata := ChannelData{infected: true, message: node.message}
         allnodes[randomnode].channel <- sentchanneldata
         fmt.Printf("Node %d sent a value of %t and %s to node %d!\n", node.number, sentchanneldata.infected, sentchanneldata.message, allnodes[randomnode].number)
    }


 //updateNodes is a function that will update the nodes values
  func updateNodes(node Node) {
    defer wg.Done()
    fmt.Printf("Updating: %d\n", node.number)
    //get value through node channel
    receivedchanneldata := <-node.channel
    fmt.Printf("Node %d received a value of %t and %s!\n", node.number, receivedchanneldata.infected, receivedchanneldata.message)
    // update value
    if receivedchanneldata.infected == true {
      node.infected = true
    }
    if receivedchanneldata.message != "" {
      node.message = receivedchanneldata.message
    }
    fmt.Printf("Update successful!\n")
  }

   //Part of main functions
    wg.Add(totalnodes)
    for node := range allnodes {
        go pushNodes(allnodes[node])
    }
    wg.Wait()
    fmt.Println("Infect function done!")

    wg.Add(totalnodes)
    for node := range allnodes {
        go updateNodes(allnodes[node])
    }
    wg.Wait()

正确答案


通道的存在(包括已推入其中的任何数据)独立于可能对其进行读取或写入的 goroutine,前提是至少有一个可以读取的 goroutine 仍然存在和/或写入它。 (一旦所有这些 goroutine 都消失了,通道最终将被 gc 回收。)

您的代码示例无法使用(如 already noted),因此我们无法准确说出您出错的位置,但您会收到在此处报告的 fatal 消息:

如果您尝试从最后一个可运行的 goroutine 中的通道读取,使得该 goroutine 进入睡眠状态以等待该通道上的消息,以这种方式go 运行时的其余部分可以确定当前休眠的 goroutine 不会醒来并在该通道上传递消息。例如,假设您总共有 7 个 goroutine 正在运行,其中一个 goroutine 到达以下代码行:

msg = <-ch

其中 ch 是一个开放通道,目前没有可用数据。这 7 个 goroutine 之一到达这一行并阻塞(“进入睡眠状态”),等待剩余的 6 goroutine 之一执行以下操作:

ch <- whatever

这会唤醒第 7 个 goroutine。所以现在只有 6 个 goroutine 可以在 ch 上写入或关闭 ch。如果剩下的六个 goroutine通过同一条线,一次一个、几个或全部,并且没有一个发送在通道上或关闭通道时,那些剩余的 goroutine 也会阻塞。当其中最后一个阻塞时,运行时会意识到程序被卡住了,并出现恐慌。

但是,如果剩下的六个 goroutine 中只有五个像这样阻塞,那么第六个 goroutine 会运行一行:

close(ch)

close 操作将关闭通道,导致所有六个“陷入睡眠”的 goroutine 接收到由零值“假”消息 msg 表示的“数据结束”。您还可以使用接收的二值形式:

msg, ok = <-ch

如果通道关闭且msg包含真实消息,则ok在此获取true,但如果通道关闭且msg现在包含零-则获取false重视“假”消息。

因此,您可以:

  • 关闭频道以表明您不打算发送任何其他内容,或者
  • 仔细匹配“从频道接收”操作的数量与“在频道上发送消息”操作的数量。

前者是通道的常态,无法提前知道应在通道上发送多少条消息。即使您知道,它仍然可以使用。完成关闭的典型构造是:

ch := make(chan T)  // for some type T
// do any other setup that is appropriate

var wg sync.WaitGroup
wg.add(N)  // for some number N
// spin off some number of goroutines N, each of which may send
// any number of messages on the channel
for i := 0; i < N; i++ {
    go doSomething(&wg, ch)
    // in doSomething, call wg.Done() when done sending on ch
}

go func() {
    wg.Wait()  // wait for all N goroutines to finish
    close(ch)  // then, close the channel
}()

// Start function(s) that receive from the channel, either
// inline or in more goroutines here; have them finish when
// they see that the channel is closed.

这种模式依赖于创建额外的第 n+1 个 goroutine 的能力,即匿名函数 go func() { ... }() 序列,其整个工作就是等待所有 发件人说我已发送完毕。每个发送者通过调用 wg.done() 一次来完成此操作。这样,发送者就没有任何关闭通道的特殊责任:他们都只是写,然后在写完后宣布“我写完了”。 一个 goroutine 有一个 特殊职责:它等待所有 发送者宣布“我写完了”,然后关闭通道然后退出,完成了一生中的一项工作。

所有接收者(无论是一个还是多个)现在都可以轻松知道何时不再有人发送任何内容,因为此时他们会看到一个关闭的通道。因此,如果大部分工作都在发送端,您甚至可以在此处使用主 goroutine 和简单的 for ... range ch 循环。

今天关于《如何从通道中读取数据一旦我的 GoRoutines 运行完毕?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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