登录
首页 >  Golang >  Go问答

Goroutines 未调用结构体上的方法

来源:stackoverflow

时间:2024-03-25 13:13:00 214浏览 收藏

在使用 Go 例程时,在结构体方法上调用时遇到问题。原本预期代码输出“第 1 项被询问是否还活着”、“第 2 项被问是否还活着”,但实际上并没有打印任何内容。当省略“go”例程(在 `struct1.isAlive()` 处)时,程序运行正常。

问题内容

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

第 1 项被询问是否还活着 第 2 项被问是否还活着

但它没有打印任何东西。当我省略“go”例程(在 struct1.isalive() 处)时,它工作正常。我怎样才能让 goroutine 工作?

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/

这是您使用 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()
}

今天关于《Goroutines 未调用结构体上的方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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