14
15:- if(\+ current_module(process_observe)). 16
17:- module(process_observe,[
18 process_observe/3,
19 process_observe/2,
20 process_unobserve/2,
21 process_notify/2,
22 process_dispatch/3
23]). 24
25:- use_module(library(debug)). 26
30:- debug(process_observe). 31
32:-dynamic process_observe_hook/3,process_unobserve_hook/3. 33:-multifile process_observe_hook/3,process_unobserve_hook/3. 34
43process_observe_hook(_,_,_):-
44 fail.
45
50process_unobserve_hook(_,_,_):-
51 fail.
52
53call_observe_hook(Thread,Subject,Key):-
54 catch(process_observe_hook(Thread,Subject,Key),E,print_message(error,E)),
55 !.
56call_observe_hook(_,_,_).
57call_unobserve_hook(Thread,Subject,Key):-
58 catch(process_unobserve_hook(Thread,Subject,Key),E,print_message(error,E)),
59 !.
60call_unobserve_hook(_,_,_).
61
62
66process_observe(Thread,Subject):-
67 term_to_atom(Subject,Key),
68 process_observe(Thread,Subject,Key).
82process_observe(Thread,Subject,Key) :-
83 recorded(process_observer,observation(Thread,OtherSubject,Key), _),
84 OtherSubject =@= Subject,
85 !.
86
87process_observe(Thread,Subject,Key) :-
89 call_observe_hook(Thread,Subject,Key),
90 recordz(process_observer,observation(Thread,Subject,Key), _).
101process_unobserve(Thread,Subject) :-
102 recorded(process_observer,observation(Thread,OtherSubject,Key),Ref),
103 OtherSubject =@= Subject,
104 erase(Ref),
105 106 call_unobserve_hook(Thread,Subject,Key).
113process_notify(Subject,Event) :-
114 debug(process_observe,'~w~n',[process_notify(Subject,Event)]),
115 forall(
116 (
117 recorded(process_observer,observation(Thread,Subject,_),Ref)
118 ),
119 ( current_thread(Thread,running)
120 -> (
121 thread_send_message(Thread,notify(Subject,Event)),
122 debug(process_observe,'~w~n',[thread_send_message(Thread,notify(Subject,Event))])
123
124 ); erase(Ref)
125 )
126 ).
136 process_dispatch(Subject,Key,Event):-
137 thread_self(Me),
138 repeat,
139 thread_get_message(notify(Subject,Event)),
140 ( Subject='$abort'
141 -> !
142 ; recorded(process_observer,observation(Me,Subject,Key), _)
143 ).
144
145
146
147:- endif.