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

时间:2018-10-03 06:37:36

标签: go

我正在尝试入门,并且遇到在结构方法上使用go例程时出现的问题。我所期望的是该代码显示以下输出:

  

询问项目1是否还活着

     

第2项被问到是否还活着

但是它没有打印任何内容。当我省去“去”例程(在struct1.isAlive()处)时,它工作正常。我如何使goroutines工作?

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 \n", 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()

1 个答案:

答案 0 :(得分:0)

问题在于程序在函数执行之前退出并打印到stdout。
一种简单的解决方法是等待两个go例程完成,然后退出主函数。
您可以参考以下链接:https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

这是使用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 \n", 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()
}