登录
首页 >  Golang >  Go问答

Golang HelloActor I 发生致命错误:所有 goroutine 在休眠中,导致死锁

来源:stackoverflow

时间:2024-02-11 22:54:24 165浏览 收藏

大家好,我们又见面了啊~本文《Golang HelloActor I 发生致命错误:所有 goroutine 在休眠中,导致死锁》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我有以下代码来使用 go 1.18 测试参与者模型

package main

import (
    "fmt"
    "sync"

    "github.com/asynkronit/protoactor-go/actor"
)

// actor

type helloactor struct{}

func (*helloactor) receive(context actor.context) {
    switch msg := context.message().(type) {
    case int:
        fmt.println(msg)
    }
}

func main() {
    system := actor.newactorsystem()
    props := actor.propsfromproducer(func() actor.actor { return &helloactor{} })

    pid := system.root.spawn(props)

    system.root.send(pid, 42)
    system.root.send(pid, 42)
    system.root.send(pid, 42)
    system.root.send(pid, 42)

    var wg sync.waitgroup    
    wg.add(1)
    wg.wait()
}

这段代码是由我的教授编写的,但由于某种原因我收到了致命错误消息。其他遇到此问题的人通常不会(正确)关闭通道,但参与者模型不会使用任何通道。 通过调试我发现程序在wg.wait()处崩溃。在 wait 方法中调用 semaquire 函数。但随后程序崩溃了。

这是确切的错误输出:

PS C:\Users\mytho\go\Verteilte Softwaresysteme\labing\ob-22ss> go run Code/proto.actor/helloworld/helloworld.go
42
42
42
42
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x10?)
        C:/Program Files/Go/src/runtime/sema.go:56 +0x25
sync.(*WaitGroup).Wait(0xc000223320?)
        C:/Program Files/Go/src/sync/waitgroup.go:136 +0x52
main.main()
        C:/Users/mytho/go/Verteilte Softwaresysteme/labing/ob-               2            
2ss/Code/proto.actor/helloworld/helloworld.go:34 +0x14f   

goroutine 6 [chan receive]:
github.com/AsynkronIT/protoactor-go/log.(*ioLogger).listenEvent(0xc000124480)
        C:/Users/mytho/go/pkg/mod/github.com/!asynkron!i!t/[email protected] 
20220403033403-f313dba2c418/log/string_encoder.go:57 +0x6d
created by github.com/AsynkronIT/protoactor-go/log.init.1
        C:/Users/mytho/go/pkg/mod/github.com/!asynkron!i!t/[email protected] 
20220403033403-f313dba2c418/log/string_encoder.go:39 +0x10a
     exit status 2

注意:这四个“42”消息仅在调试 helloactor.go 时才会显示。当它运行时,它只显示错误消息。


正确答案


var wg sync.WaitGroup    
wg.Add(1)
wg.Done()
wg.Wait()

您没有调用 wg.done() 来减少 waitgroup 计数器。

ps:sync.waitgroup 用于在主协程完成之前等待协程完成。但在您的代码中,您没有生成任何其他 goroutine,因此它没有用处。 如需参考,请查看https://pkg.go.dev/sync#WaitGroup

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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