hollywood icon indicating copy to clipboard operation
hollywood copied to clipboard

Close PID from SpawnChild

Open cowpeatechnology opened this issue 1 year ago • 0 comments

func main() {
	e, err := actor.NewEngine(actor.NewEngineConfig())
	if err != nil {
		log.Fatal(err)
	}

	pid := e.Spawn(newServer, "server", actor.WithID("server"))

	sigchld := make(chan os.Signal, 1)
	signal.Notify(sigchld, syscall.SIGINT, syscall.SIGTERM)
	<-sigchld

	wg := &sync.WaitGroup{}
	e.Poison(pid, wg)
	wg.Wait()
}

type Server struct {
}

func newServer() actor.Receiver {
	return &Server{}
}

func (s *Server) Receive(c *actor.Context) {
	switch msg := c.Message().(type) {
	case actor.Initialized:
		fmt.Println("server initialized")
	case actor.Started:
		fmt.Println("server started")

		for i := 0; i < 1; i++ {
			pid := c.SpawnChild(newServerChild(c.PID()), "client", actor.WithID(uuid.New().String()))
			//wg := &sync.WaitGroup{}
			//c.Engine().Poison(pid, wg)
			//wg.Wait()
			c.Engine().Poison(pid)
			//TODO: how can i close this pid
			time.Sleep(time.Second)
			fmt.Println(pid)
		}
	case actor.Stopped:
		fmt.Println("server stopped")
	case *actor.PID:
		//c.Engine().Poison(c.Sender())
	default:
		fmt.Printf("%v\n", msg)
	}
}

type ServerChild struct {
	ServerPid *actor.PID
}

func newServerChild(ServerPid *actor.PID) actor.Producer {
	return func() actor.Receiver {
		return &ServerChild{
			ServerPid: ServerPid,
		}
	}
}

func (sc *ServerChild) Receive(c *actor.Context) {
	switch msg := c.Message().(type) {
	case actor.Initialized:
		fmt.Println("serverChild initialized")
	case actor.Started:
		fmt.Println("serverChild started")
		//c.SpawnChild(newTimer(), "Timer")
	case actor.Stopped:
		fmt.Println("serverChild stopped")
	case *actor.PID:
		fmt.Println("serverChild got timer")
	default:
		fmt.Printf("%v\n", msg)
	}
}

This code will deadlock when poison server's pid, how should I gracefully close a pid from SpawnChild?

cowpeatechnology avatar Jan 16 '24 10:01 cowpeatechnology