[erlang-questions] Mnesia and concurrency

Ulf Wiger ulf@REDACTED
Sat Dec 23 00:37:53 CET 2006


Den 2006-12-22 19:35:15 skrev Yariv Sadan <yarivvv@REDACTED>:

> How could one implement such a thing in Erlang? Assuming a table is
> owned by a single process, and that process can only accept one
> message at a time, how can multiple processes perform simultaneous
> reads on the table?

A normal way to provide concurrent access to a critical
region in Erlang is to use a process to serialize the
accesses. This is really not much different from guarding
a critical region using semaphores - only much simpler.
It is also quite fast.

Mnesia uses ets (or dets) tables, which can be accessed
concurrently by different processes. All reads and writes
are atomic, which means that they are serialized at the
lowest level (similar to always using write locks in a
threaded application).

Mnesia goes one step further. The thing that needs
protecting in a DBMS isn't necessarily just individual
reads and writes, but the whole transaction, possibly
writing data to different tables that in its turn
depends on data written from other tables. To do this,
mnesia has a locker - a server process on each mnesia
node, which is responsible for serving read- write- and
table locks to different mnesia transactions.

When claiming a series of write locks, there is a risk
of different transactions getting caught in circular wait
situations - deadlock. To avoid this, mnesia uses a
technique called "deadlock prevention", which basically
means that dependencies can only be uni-directional, and
if a transaction violates this, it is restarted. This is
ok, as long as the transaction is not doing funny stuff
like message passing, or reading and writing to ets tables
outside of mnesia. Mnesia takes care of rolling back and
re-executing all updates done by the transaction that is
restarted, but beyond that, the mnesia user has to play
nice and not do anything they're not supposed to.

So, at the lowest levels, readers and writers locking is
done, but there is much more to it than that in a full-
fledged DBMS.

BR,
Ulf W
-- 
Ulf Wiger



More information about the erlang-questions mailing list