bezzoon
bezzoon

Reputation: 2019

How to iterate through many GenServers of the same type?

Problem: I have a type FlyServer and need to iterate through all the Fly processes. For various computations on the server.

How do I accomplish this?

One option is to have a GenServer list of all the FlyServer processes. But what if it crashes? And what if a player crashes and for whatever reason the GenServer keeping track of the processes isn't notified --- chime in if that scenario is unrealistic please.

Upvotes: 1

Views: 116

Answers (2)

7stud
7stud

Reputation: 48589

  1. Every time a Fly process contacts the server, you can add its pid to a list, where the list is part of the gen_server's State.

  2. The server can then monitor the Fly process, which means that when a Fly process terminates, the server will get sent a special message.

  3. The server can implement a receive clause that pattern matches the special message and then removes the terminated process's pid from the list.

One option is to have a GenServer list of all the FlyServer processes. But what if it crashes?

Then terminate(Reason, State) will be called in the callback module, which can save State to an ets, dets, or mnesia table. Of course, if someone trips over the cord that connects the server running the FlyServer to an electrical outlet, then execution will immediately halt and terminate() will not be called. See distributed erlang for solutions.

Upvotes: 2

Pascal
Pascal

Reputation: 14042

I advise you to start your servers using a supervisor with a call to supervisor:start_child/2. The supervisor should use the strategy simple_one_for_one which is meant to create and supervise processes of the same kind.

Then you can get an updated list of all the chidren using the function supervisor:which_children/1

Upvotes: 4

Related Questions