% :- ensure_loaded(common).
% cvs_id('$Id: mt.pl,v 1.5 2004/10/15 21:57:56 sandro Exp $').
/*

  Let's make multi-thread safe versions of db_* and rdf*....


   DOESNT HANDLE EXCEPTIONS, I THINK.    NO FREE THEN.


  
*/

:- ensure_loaded(library(debug)).

mutex_lock_visible(M) :-
	thread_self(Self),
	/*

	   recursive mutex can legit occur when doing a join.
	  
	(   current_mutex(MM, SS, _),
	    MM = M,
	    SS = Self
	->  stack_trace(Lines),
	    print_message_lines(user_error, '', Lines),
	    throw(recursive_mutex)
	;   true
	),
	*/
	flag(Self, OldStatus, M),
	mutex_lock(M),
	flag(Self, _, OldStatus),
	!.
mutex_lock_visible(_) :-
	stack_trace(Lines),
	print_message_lines(user_error, '', Lines),
	throw(mutex_lock_vis_failed).

mt_rdf(A,B,C,D) :-
	mutex_lock_visible(rdf_mutex),
	call_cleanup(rdf_db:rdf(A,B,C,D),
		     mutex_unlock(rdf_mutex)).

mt_rdf_assert(A,B,C,D) :-
	mutex_lock_visible(rdf_mutex),
	call_cleanup(rdf_db:rdf_assert(A,B,C,D),
		     mutex_unlock(rdf_mutex)).

mt_rdf_retractall(A,B,C,D) :-
	mutex_lock_visible(rdf_mutex),
	call_cleanup(rdf_db:rdf_retractall(A,B,C,D),
		     mutex_unlock(rdf_mutex)).

mt_rdf_update(A,B,C,D) :-
	mutex_lock_visible(rdf_mutex),
	call_cleanup(rdf_db:rdf_update(A,B,C,D),
		     mutex_unlock(rdf_mutex)).


mt_db_get(A,B,C) :-
	mutex_lock_visible(db_mutex),
	call_cleanup(db:db_get(A,B,C),
		     mutex_unlock(db_mutex)).

mt_db_put(A,B,C) :-
	mutex_lock_visible(db_mutex),
	call_cleanup(db:db_put(A,B,C),
		     mutex_unlock(db_mutex)).

mt_db_open(A,B,C) :-
	mutex_lock_visible(db_mutex),
	call_cleanup(db:db_open(A,B,C),
		     mutex_unlock(db_mutex)).

mt_db_close(A) :-
	mutex_lock_visible(db_mutex),
	call_cleanup(db:db_close(A),
		     mutex_unlock(db_mutex)).


mt_db_delall(A,B,C) :-
	mutex_lock_visible(db_mutex),
	call_cleanup(db:db_delall(A,B,C),
		     mutex_unlock(db_mutex)).


mt_db_enum(A,B,C) :-
	mutex_lock_visible(db_mutex),
	call_cleanup(db:db_enum(A,B,C),
		     mutex_unlock(db_mutex)).



