/** Threads - implements triggers, timers and simultaneous actions. @author Piotr Hołownia */ :- module(threads,[ trigger_create/3, timer_create/3, do_simultaneously/1 ]). %% trigger_create(-ID,+Event,+Action). % % Creates trigger. % Action will be fired, when Event is true. % Action can be both predicate and list of predicates. trigger_create(ID,Event,Action) :- thread_create(trigger(Event,Action),ID,[]). fired([Action|Tail]) :- Action, fired(Tail). fired([Action]) :- Action. fired(Action) :- Action. trigger(Event,Action) :- Event, fired(Action). trigger(Event,Action) :- trigger(Event,Action). %% timer_create(-ID,+Time,+Action). % % Creates timer. % Action will be fired after specified Time. % Action can be both predicate and list of predicates. timer_create(ID,Time,Action) :- get_time(Start_time), Finish_time is Start_time+Time, thread_create(timer(Finish_time,Action),ID,[]). timer(Finish_time,Action) :- get_time(Time), Time >= Finish_time, fired(Action). timer(Finish_time,Action) :- timer(Finish_time,Action). %% do_simultaneously(+Action) % % Creats a thread for each action from Action. % Last of them runs in the main thread. % Action should be a list of predicates. % Although Action can be a signle predicate it makes no sense. do_simultaneously([Action|Tail]) :- thread_create(Action,_,[]), do_simultaneously(Tail). do_simultaneously([Action]) :- Action. do_simultaneously(Action) :- Action.