dongyan1808 2018-10-03 06:37
浏览 11
已采纳

当调用结构上的方法时,goroutines不起作用

This question already has an answer here:

I'm trying to get into go and I'm facing a problem which appears when using go routines on a method of a struct. What I was expecting is that the code prints the following output:

Item 1 was asked if it's alive

Item 2 was asked if it's alive

But it's not printing anything. When I leave out the "go"routines (at struct1.isAlive()) it's working fine. How can I make the goroutines work?

package main

import (
    "fmt"
)

type somestruct struct {
    ID              int
    ItemName        string
}

func (s *somestruct) isAlive() (alive bool) {
    alive = true
    fmt.Printf("%s was asked if it's alive 
", s.ItemName)
    return
}


func main() {
    struct1 := somestruct{
        ID:1,
        ItemName:"Item 1"}

    struct2 := somestruct{
        ID:2,
        ItemName:"Item 2"}


    go struct1.isAlive()
    go struct2.isAlive()
</div>
  • 写回答

1条回答 默认 最新

  • duanmi3476 2018-10-03 06:43
    关注

    The Issue is that the program exits before the functions could execute and print out to stdout.
    One simple fix is to wait for both of the go routines to finish and then exit from main function.
    Here is a link that you can refer : https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

    here is your program implemented with WaitGroups

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    type somestruct struct {
        ID       int
        ItemName string
        wg       *sync.WaitGroup
    }
    
    func (s *somestruct) isAlive() (alive bool) {
        defer s.wg.Done()
        alive = true
        fmt.Printf("%s was asked if it's alive 
    ", s.ItemName)
        return
    }
    
    func main() {
        var wg sync.WaitGroup
        wg.Add(2)
        struct1 := somestruct{
            ID:       1,
            ItemName: "Item 1",
            wg:       &wg,
        }
    
        struct2 := somestruct{
            ID:       2,
            ItemName: "Item 2",
            wg:       &wg,
        }
    
        go struct1.isAlive()
        go struct2.isAlive()
        wg.Wait()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改