unfode

unfode

Suppose I have two states. In C, I can mutate them atomically (either all or none are mutated) using locks:

bool atomic_mutation() {
  lock(state1_lock);
  lock(state2_lock);

  bool success = mutate1(state1);
  if (!success) {
    unlock(state1_lock);
    unlock(state2_lock);
    return false;
  }

  success = mutate2(state2);
  if (!success) {
    // revert mutate1(state1)
    unlock(state1_lock);
    unlock(state2_lock);
    return false;
  }

  unlock(state1_lock);
  unlock(state2_lock);
  return true;
}

I’m new to Elixir. What I’ve learned is that I normally use an Agent to manage a state. But how to achieve atomicity shown above in Elixir? Thanks!

Edit: I fixed the bug in the C code above as pointed out by @al2o3cr

Showing Posts 1 to 10

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hey welcome! The short answer is that if you need shared state and you need to control changes to that state then yeah you would use an agent or GenServer (more generally) and put the state inside that.

In general though as a functional language much of your program design will be avoiding such shared state at all.

unfode

unfode OP

I understand that the functional style avoids shared states as much as possible. But shared states can’t be eliminated in many applications, like databases.

Suppose I have two tables in a database. I need to mutate both tables atomically in a transaction. How to achieve this in Elixir using Agent or GenServer?

One solution is to have an Agent manage both tables as one state. However, the downside is poor performance — when processA mutates table1 and processB mutates table2, the two mutations can’t be done in parallel, even if they are independent of each other.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

I would simply use the database itself for this, it will provide a ton of dedicated tooling for it.

LostKobrakai

LostKobrakai

How do you make sure multiple actors changes are actually independent?

In the end you’ll surely get to the fact that immutability prevents certain optimizations, but generally the question should be how much those matter to the endproduct.

unfode

unfode OP

In the end you’ll surely get to the fact that immutability prevents certain optimizations, but generally the question should be how much those matter to the endproduct.

Good point.

How do you make sure multiple actors changes are actually independent?

Mutations of two tables seem surely independent. Can you provide an example?

unfode

unfode OP

Maybe someone wants to build a database in Elixir :slight_smile:

LostKobrakai

LostKobrakai

Put each table in a separate process and they’re independent.

dimitarvp

dimitarvp

  • Put the state inside a GenServer.
  • Have it receive messages like :modify_twenty_things_inside_the_state.
  • Modify stuff together in the message handler, to your heart’s content.
  • ???
  • Profit.

Or if a database need be involved, they have their own transaction primitives as others said.

al2o3cr

al2o3cr

The BEAM provides the infrastructure, but you need to write the code to glue things together into a consistent distributed system - and to be clear, once you have TWO GenServers you’re trying to make change together you’re in distributed-system territory.

For instance, here’s a very basic “table with a lock” GenServer (see below for notes):

defmodule TableWithLock do
  use GenServer

  defstruct [:data, :owner]

  def unlock(pid), do: GenServer.call(pid, :unlock)
  def lock(pid), do: GenServer.call(pid, :lock)
  def update(pid, fun), do: GenServer.call(pid, {:update, fun})

  @impl true
  def init(data) do
    {:ok, %__MODULE__{data: data, owner: nil}}
  end

  @impl true
  def handle_call(:lock, {pid, _tag}, state) do
    cond do
      is_nil(state.owner) ->
        # unlocked, pid now owns lock
        {:reply, :ok, %{state | owner: pid}}

      state.owner == pid ->
        # already locked by pid
        {:reply, :ok, state}

      true ->
        # locked by another process
        raise "oh no lock contention"
    end
  end

  def handle_call(:unlock, {pid, _tag}, state) do
    cond do
      is_nil(state.owner) ->
        # already not locked
        raise "somebody already unlocked this???"

      state.owner == pid ->
        # locked by the caller
        {:reply, :ok, %{state | owner: nil}}

      true ->
        # locked by somebody else
        raise "unlocking somebody else's lock"
    end
  end

  def handle_call({:update, fun}, {pid, _tag}, state) do
    cond do
      is_nil(state.owner) ->
        # not locked
        raise "not locked"

      state.owner == pid ->
        # locked by the caller
        result = fun.(state.data)
        {:reply, result, %{state | data: result}}

      true ->
        # locked by somebody else
        raise "updater not holding the lock"
    end
  end
end

{:ok, pid1} = GenServer.start_link(TableWithLock, [1,2,3])

:ok = TableWithLock.lock(pid1)

result = TableWithLock.update(pid1, fn data -> Enum.map(data, & &1*2) end)

:ok = TableWithLock.unlock(pid1)

IO.inspect(result)

There are a LOT of places where this could be work better / handle concurrency better:

  • crashing the table when a second process tries to take the lock is not realistic. A better implementation would keep a queue of pids that are currently trying to take the lock in lock and pick the next one to reply to in unlock.
  • crashing the table on bogus unlocks isn’t realistic either. An alternative would be to return something from handle_call that the implementation of unlock/1 could use to crash the calling process, since unlocking a table that you haven’t locked is a logic error
  • if a process dies while holding the lock, it will never be unlocked. Tools like Process.monitor can help with this, at the cost of additional complexity.

Expanding this setup to TWO tables adds some extra complications:

  • if process A takes lock 1 and then tries to take lock 2, while at the same time process B takes lock 2 and tries to take lock 1 the system is in a classic DEADLOCK situation. The default 5s timeout on GenServer.call will eventually pick a winner, but real systems will detect this and complain

  • coordinating changes to ensure that they either all appear or all do not is still just as tricky as always. You’d need a third process to coordinate the TableWithLocks and roll back changes if a future change fails.

    Note that even the code in your example does not produce atomicity - if mutate2 returns false, the changes from mutate1 are still visible.

    Solving this problem correctly is capital-H Hard and the solutions are highly sensitive to exactly what tradeoffs your particular application can tolerate.

unfode

unfode OP

Really appreciate your comprehensive answer!

Where Next? Top

Trending in Questions Top

RSP87
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
nseaSeb
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
RemyXRenard
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
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
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
samoloth
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
FlyingNoodle
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 Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews