在mnesia中,有脏读脏写等以及事物读写,它们的差异通过测试不难发现:
代码如下:
-module(mnesia_read_test). -compile(export_all). -record(r_test, {id, name}). start(N) -> timer:tc(mnesia_read_test,dirty_read,[N]). start2(Num) -> timer:tc(mnesia_read_test,t_read,[Num]). init() -> case mnesia:create_schema([node()]) of ok -> ok; _ -> mnesia:delete_schema([node()]), mnesia:create_schema([node()]) end, mnesia:start(), case mnesia:create_table(r_test, [{attributes, record_info(fields, r_test)}, {record_name, r_test},{disc_copies, [node()]}]) of {atomic, ok} -> ok; _Any1 -> mnesia:delete_table(r_test), mnesia:create_table(r_test, [{attributes, record_info(fields, r_test)}, {record_name, r_test},{disc_copies, [node()]}]) end, mnesia:transaction(fun() -> t_write(10000) end). t_write(0) -> ok; t_write(N) -> Name = lists:append(["name_", N]), R = #r_test{id=N, name=Name}, mnesia:write(R), t_write(N-1). dirty_read(0) -> ok; dirty_read(Num) -> mnesia:dirty_read(r_test, Num), dirty_read(Num-1). t_read(0) -> ok; t_read(Num) -> mnesia:transaction( fun() -> mnesia:read(r_test, Num) end), t_read(Num-1).
%%这里创建的表类型为:disc_copies
{disc_copies,NodeList} NodeList每个节点都有内存备份和磁盘备份
测试结果如下:
不难发现,脏读比事物读快了至少1个——2个数量级,获取的结果为微秒(1秒 = 1000000微秒)
从mnesia.erl 追踪脏读源码到mnesia_lib.erl中:
db_get(Tab, Key) ->
db_get(val({Tab, storage_type}), Tab, Key).
db_get(ram_copies, Tab, Key) -> ?ets_lookup(Tab, Key);
db_get(disc_copies, Tab, Key) -> ?ets_lookup(Tab, Key);
db_get(disc_only_copies, Tab, Key) -> dets:lookup(Tab, Key).
发现是ets直接操作。