You have nothing to worry about. From the mnesia documentation:
Reading locks can be general, which means that if one transaction succeeds in obtaining a read lock on an item, other transactions can also get a read lock on the same item. However, if someone has a read lock, no one can get a write lock on the same element. If someone has a write lock, no one can get a read lock and write lock in the same element.
If a transaction has a read lock on an object, this object cannot be edited by another transaction.
Let's say you have two transactions: T1 and T2, which are executed in parallel:
- T1 does
mnesia:match_object and gets a read lock for all returned objects. - T2 does the equivalent of
mnesia:match_object and gets a read lock on the same objects. - T2 tries to get a write lock on objects (for editing it).
- Mnesia will automatically abort T2 to try again later.
- T1 gets a write lock for objects and edits them.
- T1 ends.
- Mnesia repeats T2.
Note that T2 can be repeated several times, depending on how long T1 takes (i.e. release its locks).
According to my tests, the mnesia:match_object blocking behavior is incompatible. For example, mnesia:match_object(mytable, {mytable, 2, '_'}, LockType) will only lock the record with key 2, but mnesia:match_object(mytable, {mytable, '_', test}, LockType) block all table.
Also note that the documentation is incorrect, mnesia:match_object(Table, Pattern, write) works, and seems to follow the same pattern as read, i.e. if you specify a key, only the corresponding record will be locked; if you do not specify a key, the entire table will be locked for writing.
You can verify this yourself by doing something like this:
test() -> mnesia:transaction(fun()-> Table = mytable, Matches = mnesia:match_object(Table, {Table, 2, '_'}, write), io:format("matched: ~p~n", [Matches]), spawn(fun()->mnesia:transaction(fun()-> io:format("trying to read~n",[]), io:format("read: ~p~n", [mnesia:read(Table, 2, read)]) end) end), timer:sleep(1000), RereadMatches = lists:map(fun(
By changing the pattern and lock type passed to match_object and the key number and lock type passed to mnesia:read in the spawned process (or using mnesia:write ), you can test various locking actions.
Addendum: See this post by Ulf Wieger on the same topic.
Appendix 2: See the โInsulationโ section of the Mnesia User Guide.
Edit: Above everything was done in the set table, match_object locking behavior may be different in the bag type table.