14
19
20:- module(process_observe,[
21 process_observe/3,
22 process_observe/2,
23 process_unobserve/2,
24 process_notify/2,
25 process_dispatch/3
26]). 27
28:- use_module(library(debug)). 29
30:-dynamic process_observe_hook/3,process_unobserve_hook/3. 31:-multifile process_observe_hook/3,process_unobserve_hook/3. 32
41process_observe_hook(_,_,_):-
42 fail.
43
48process_unobserve_hook(_,_,_):-
49 fail.
50
51call_observe_hook(Thread,Subject,Key):-
52 catch(process_observe_hook(Thread,Subject,Key),E,print_message(error,E)),
53 !.
54call_observe_hook(_,_,_).
55call_unobserve_hook(Thread,Subject,Key):-
56 catch(process_unobserve_hook(Thread,Subject,Key),E,print_message(error,E)),
57 !.
58call_unobserve_hook(_,_,_).
59
60
64process_observe(Thread,Subject):-
65 term_to_atom(Subject,Key),
66 process_observe(Thread,Subject,Key).
80process_observe(Thread,Subject,Key) :-
81 recorded(process_observer,observation(Thread,OtherSubject,Key), _),
82 OtherSubject =@= Subject,
83 !.
84
85process_observe(Thread,Subject,Key) :-
87 call_observe_hook(Thread,Subject,Key),
88 recordz(process_observer,observation(Thread,Subject,Key), _).
99process_unobserve(Thread,Subject) :-
100 recorded(process_observer,observation(Thread,OtherSubject,Key),Ref),
101 OtherSubject =@= Subject,
102 erase(Ref),
103 104 call_unobserve_hook(Thread,Subject,Key).
111process_notify(Subject,Event) :-
112 debug(process_observe,'~w~n',[process_notify(Subject,Event)]),
113 forall(
114 (
115 recorded(process_observer,observation(Thread,Subject,_),Ref)
116 ),
117 ( current_thread(Thread,running)
118 -> (
119 thread_send_message(Thread,notify(Subject,Event)),
120 debug(process_observe,'~w~n',[thread_send_message(Thread,notify(Subject,Event))])
121
122 ); erase(Ref)
123 )
124 ).
134 process_dispatch(Subject,Key,Event):-
135 thread_self(Me),
136 repeat,
137 thread_get_message(notify(Subject,Event)),
138 ( Subject='$abort'
139 -> !
140 ; recorded(process_observer,observation(Me,Subject,Key), _)
141 )