'Golang HelloActor I fatal error: all goroutines are asleep - deadlock

I have the following Code to test the actor-model with 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()
}

This Code was written by my professor but for some reason I get the fatal error message. Other people who have this problem often don't (properly) close channels but the actor-model does not use any. Through debugging I found out that the programm crashes at wg.Wait(). Within the Wait-method is a call of the semaquire function. But then the programm crashes.

Here is the exact error output:

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

NOTE: the four "42" messages are only shown when the helloactor.go is debugged. When it is being runned it only shows the error-message.



Solution 1:[1]

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

You are not calling wg.Done() to decrement the WaitGroup counter.

PS: sync.WaitGroup is used to wait for goroutines to finish before the main goroutine completes. But in your code, you are not spawning any other goroutine so it has no use. For reference, check https://pkg.go.dev/sync#WaitGroup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhay Pratap Singh