affq19
Hi! I’ve been studying concurrency models with elixir. Now, I want to develop a ChatRoom, where users can Join, post messages, and disconnect themselves using threads and mutex in elixir. So far I have developed the model for entering new users and disconnect them. However, I have put some “prints” to see how its working, but they are not showing when I run the program. This is the code,
defmodule MyMutex do
@mutex :free
def lock(:free) do
{:ok, :locked}
end
def lock(:locked) do
{:error, :already_locked}
end
def unlock(:locked) do
:ok
end
def unlock(:free) do
{:error, :not_locked}
end
end
defmodule Chat do
defstruct users: [], messages: [], mutex: MyMutex
def start_link() do
{:ok, pid} = Task.start_link(fn -> action(%__MODULE__{}) end)
end
defp action(chat) do
receive do
{:join, :user} ->
chat = new_user(chat, :user)
action(chat)
#{:post, user} ->
# chat = post_message(chat, user)
# action(chat)
{:disconnect, user} ->
chat = disconnect_user(chat, user)
action(chat)
{:users_chat} ->
post_all_users(chat)
action(chat)
end
end
defp post_all_users(chat) do
Enum.each(chat.users, fn user ->
"User:"
end)
end
defp post_message_to_all(chat, message) do
Enum.each(chat.users, fn user ->
IO.puts("Message from server: #{message} (Sent to: #{user})")
end)
end
defp new_user(chat ,user) do
{:ok, mutex} = MyMutex.lock(chat.mutex)
updated_chat = %{ chat | users: chat.users ++ [user], mutex: mutex }
IO.puts("Entering the chat: #{user}")
MyMutex.unlock(mutex)
post_message_to_all(updated_chat, "#{user} has joined the chat.")
updated_chat
end
defp disconnect_user(chat, user) do
{:ok, mutex} = MyMutex.lock(chat.mutex)
chat = %{chat | users: List.delete(chat.users, user),
mutex: mutex}
IO.puts("The user #{user} has leaved the chat")
MyMutex.lock(mutex)
chat
end
end
Thanks in Advice ![]()
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
kokolegorille
Hello and welcome,
Do You really need mutex in Elixir?
You might be interested by this YT video
by @geo
dimitarvp
What was your education source that claimed you need mutexes in Elixir?
You don’t need them here.
arijoon
I have to agree with other posters regarding mutex. General usecase for a mutex is to lock a shared resource when multiple threads are writing to it. In erlang we have processes which do not share resources. If you wish to share something (for example the chat messages), you can create a new process which holds this information and read/write to it by sending messages to that process. Since the process will only action one message at a time, no mutex will be required
affq19
Thanks. However, I do not see how can I do that. So far I’m trying to store the messages in a structure but I´m having problems with that
affq19
Well, It was a recommendation, however I’m open to hear more, I have tried several things and it does not work
tomg
Sounds like you need a GenServer to manage your state. And since it’s based on a single BEAM process, there’s no need for synchronization.
voughtdq
Ok, let’s just go with the mutex idea for this, but with the understanding that you generally don’t need them in Elixir. It can be a little frustrating to have someone tell you “don’t do x” because sometimes doing it wrong first helps us learn to do it right.
You’ve started with a task, which is a process. So you’re moving in the right direction. Having that receive loop inside the task will allow you to manage state. In general, we wouldn’t use a task for this - either a process with
Process.spawn/1or aGenServerwhen it gets more complex, but we can accomplish what you want inside the task.Can you tell us what you’re trying and what you expect to happen? I notice a few issues in your
new_user/2anddisconnect_user/2where you’re throwing away the mutex values. What functions are you calling and what is supposed to print?dimitarvp
Do you know of
GenServer?affq19
I want to print the entering messages and users that enters the chat, and I’m not calling any functions inside those that you mention I’m just changing the values of the struct
voughtdq
What do you mean? How do you know whether it is or isn’t working? How are you running this code?