How to model users as processes with custom names

Hi, I’m learning Elixir so for the moment keep in mind I have no idea what I’m talking about.

With that caveat out of the way…

I want to create a code example where a “user” is modeled as a process and each process has some data associated with it. The code I came up with is below. The problem I am having is that each Agent’s custom name is an atom. Because its an atom, it can not be dynamically created. Ideally I wanted to connect my code to a web server and when a user logs in they in effect “are” a dynamically created Agent. From the look of things, it seems this entire outlook is a complete dead end. Below is my code and I am curious if anyone has any advice for how I should be looking at this problem to set me straight. Thanks a bunch

Keep in mind these are just exercises for me to learn Elixir.

#____________________________________________________________BEGIN Module

defmodule App do
	def makeUser(name) do
		{:ok, item} = Agent.start_link fn -> [] end
		pid = elem({:ok, item}, 1)
		Process.register(pid, name)
	end
end

#____________________________________________________________END module



App.makeUser(:Bob) #:::: Set new user

#____________________________________________________________BEGIN update data examples

Agent.update(:Bob, fn list -> [%{thing: "stuff"} | list] end)
Agent.update(:Bob, fn list -> ["capture the flag" | list] end)

#____________________________________________________________END update data examples 

IO.inspect Agent.get(:Bob, fn list -> list end)

IO.inspect Process.whereis(:Bob)  # use name to get PID

IO.inspect Process.registered # find all registered processes

In fact, you can create atoms dynamically, but you really shouldn’t due to the hard runtime limitation of a maximum of ~1000000 atoms. https://hexdocs.pm/elixir/String.html#to_atom/1

Also there are some libraries available, which do allow arbitrary erlang/elixir terms as names for processes, but introduce some overhead. One of the most used and matured might be erlangs gproc, as it is used for quite a while now. But I neither used it myself so far as well as I am not aware of any wrappers.

In Elixir 1.4 there is also the Registry-module, which should also be capable of process registration as it looks like from the first examples I do see there.

Thanks for this.

I also found this article which looks very useful:

1 Like