%%%----------------------------------------------------------------------
%%% File    : mnesia_deadlock.erl
%%% Author  : Luke Gorrie <luke@not-a-domain.com>
%%% Purpose : Try to induce a lot of deadlocks into Mnesia to see if it'd
%%%           be useful to add "upgrade" locks.
%%% Created :  9 Aug 1999 by Luke Gorrie <luke@not-a-domain.com>
%%%----------------------------------------------------------------------

-module(mnesia_deadlock).
-author('luke@not-a-domain.com').

-record(test_rec, {id=1, date=now()}).

-export([init/0,run_test/1,cleanup/0, transaction/2]).

init() ->
    mnesia:create_table(test_rec,
			[{attributes, record_info(fields, test_rec)}]),
    mnesia:transaction(fun() -> mnesia:write(#test_rec{}) end).

cleanup() ->
    mnesia:delete_table(test_rec).

run_test(N) ->
    Deadlocker =
	fun() ->
		mnesia:write(#test_rec{})
	end,
    spawn_worker(N, Deadlocker),
    wait_responses(N).

spawn_worker(0, _F) ->
    ok;
spawn_worker(N, F) ->
    spawn_link(?MODULE, transaction, [self(), F]),
    %transaction(self(), F),
    spawn_worker(N-1, F).

wait_responses(0) ->
    ok;
wait_responses(N) ->
    receive
	finished ->
	    wait_responses(N-1)
    end.

transaction(Pid, F) ->
    {atomic, _} = mnesia:transaction(F),
    Pid ! finished.

