mnesia的锁,分为读锁、写锁等,本次总结一下,在一个事务中,什么操作会触发锁。
做如下实验:
实验一:事务中,先读后写,读写之间又10s中等待;
write(Name) ->
Fun = fun() ->
[{person, Name, Age}] = mnesia:read(person, Name),
io:format("read ok, Name=~p, Age=~p~n", [Name, Age]),
timer:sleep(10000),
mnesia:write({person, Name, Age+1})
end,
{atomic, ok} = mnesia:sync_transaction(Fun).
test2() ->
erlang:spawn(?MODULE, write, ["Andy"]),
% timer:sleep(1000),
erlang:spawn(?MODULE, write, ["Andy"]),
io:format("over!~n"),
timer:sleep(10000),
ok.
结论:
1. 读数据时,会触发读锁
2. 读锁不影响进程2的读表操作
实验二:事务中,先读后写,写后等待10s,再结束事务;
write(Name) ->
Fun = fun() ->
[{person, Name, Age}] = mnesia:read(person, Name),
io:format("read ok, Name=~p, Age=~p~n", [Name, Age]),
Result = mnesia:write({person, Name, Age+1}),
timer:sleep(10000),
Result
end,
{atomic, ok} = mnesia:sync_transaction(Fun).
test2() ->
erlang:spawn(?MODULE, write, ["Andy"]),
timer:sleep(1000),
erlang:spawn(?MODULE, write, ["Andy"]),
io:format("over!~n"),
timer:sleep(10000),
ok.
结论:
1. 写数据时,触发写锁,直到事务结束,才会释放锁
2. 写锁,会延迟进程2的读表操作
实验三:修改实验一的读表语句,手动修改锁为写锁;
write(Name) ->
Fun = fun() ->
[{person, Name, Age}] = mnesia:read(person, Name, write),
io:format("read ok, Name=~p, Age=~p~n", [Name, Age]),
timer:sleep(10000),
mnesia:write({person, Name, Age+1})
end,
{atomic, ok} = mnesia:sync_transaction(Fun).
test2() ->
erlang:spawn(?MODULE, write, ["Andy"]),
% timer:sleep(1000),
erlang:spawn(?MODULE, write, ["Andy"]),
io:format("over!~n"),
timer:sleep(10000),
ok.
结论:
1. 同样印证了,写锁会延迟其他进程的读写操作,直到事务结束,才会释放锁