liveBook · Manning

:global.trans/2

As explained in Elixir in Action, Third Edition

:global.trans/2 is an Erlang function that acquires a distributed lock, executes a function, and releases the lock.

:global.trans/2 coordinates a cluster-wide critical section: it acquires a distributed lock, runs a function, and releases the lock afterward. A lock identifier such as {:some_resource, self()} distinguishes the requester; using a process ID allows at most one process to hold that lock. section 12.1.5

Serializing large-data processing

def process(large_data) do :global.trans( {:some_resource, self()}, fn -> do_something_with(large_data) end ) end This serializes the operation across the cluster without first sending the large data to a synchronization process. section 12.1.5

Use locks judiciously: excessive locking can produce deadlocks, livelocks, or starvation. Process-based synchronization is generally easier to reason about, while a lock can avoid the serialization, transmission, and copying costs of passing large messages between nodes. section 12.1.5

def process(large_data) do
  :global.trans(                     #1
    {:some_resource, self},
    fn ->
      do_something_with(large_data)  #2
    end
  )
end

View the runnable Elixir-shaped acquire, execute, and release pattern. section 12.1.5

How Elixir in Action, Third Edition covers it

How deep it goes
Explains lock identity, blocking acquisition, automatic release, and trade-offs without detailing lock internals.
Examples
Demonstrates serializing large-data processing across nodes with a resource key and process identifier.
What it assumes
Assumes familiarity with distributed nodes, processes, process identifiers, and function execution.
What you can do after
Apply it via :global.trans/2 to wrap a cluster-wide critical section and release its lock after execution.
How it connects
Connects distributed locks with processes, message passing, deadlocks, livelocks, starvation, and distributed systems.

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.