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



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

项目1被问到它是否还活着

项目2被问及它是否还活着

但它没有打印任何东西。当我省略"go"例程(在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()

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

这是您使用候组实施的计划

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()
}