O'Reilly logo

Erlang Programming by Francesco Cesarini, Simon Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transactions

As many concurrent processes, possibly located on different nodes, can access and manipulate objects at the same time, you need to protect the data from race conditions. You do this by encapsulating the operations in a fun and executing them in a transaction. A transaction guarantees that the database will be taken from one consistent state to another, that changes are persistent and atomic across all nodes, and that transactions running in parallel will not interfere with each other. In Mnesia, you execute transactions using:

mnesia:transaction(Fun)

where the fun contains operations such as read, write, and delete. If successful, the call returns a tuple {atomic, Result}, where Result is the return value of the last expression executed in the fun. If the transaction fails, {aborted, Reason} is returned. Always pattern-match on {atomic, Result}, as your transactions should never fail unless mnesia:abort(Reason) is called from within the transaction.

Make sure your funs, with the exception of your Mnesia operations, are free of side effects. When executing your fun in a transaction, Mnesia will put locks on the objects it has to manipulate. If another process is holding a conflicting lock on an object, the transaction will first release all of its current locks and then restart. Side effects such as an io:format/2 call, or sending a message, might result in the printout or the message being sent hundreds of times.

Writing

To write an object in a table, you use the function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required