View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2007-2020, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(thread,
   38          [ concurrent/3,               % +Threads, :Goals, +Options
   39            concurrent_maplist/2,       % :Goal, +List
   40            concurrent_maplist/3,       % :Goal, ?List1, ?List2
   41            concurrent_maplist/4,       % :Goal, ?List1, ?List2, ?List3
   42            first_solution/3,           % -Var, :Goals, +Options
   43
   44            call_in_thread/2            % +Thread, :Goal
   45          ]).   46:- autoload(library(apply),[maplist/2,maplist/3,maplist/4,maplist/5]).   47:- autoload(library(debug),[debug/3]).   48:- autoload(library(error),[must_be/2]).   49:- autoload(library(lists),[subtract/3,same_length/2]).   50:- autoload(library(option),[option/3]).   51
   52
   53%:- debug(concurrent).
   54
   55:- meta_predicate
   56    concurrent(+, :, +),
   57    concurrent_maplist(1, +),
   58    concurrent_maplist(2, ?, ?),
   59    concurrent_maplist(3, ?, ?, ?),
   60    first_solution(-, :, +),
   61    call_in_thread(+, 0).   62
   63
   64:- predicate_options(concurrent/3, 3,
   65                     [ pass_to(system:thread_create/3, 3)
   66                     ]).   67:- predicate_options(first_solution/3, 3,
   68                     [ on_fail(oneof([stop,continue])),
   69                       on_error(oneof([stop,continue])),
   70                       pass_to(system:thread_create/3, 3)
   71                     ]).

High level thread primitives

This module defines simple to use predicates for running goals concurrently. Where the core multi-threaded API is targeted at communicating long-living threads, the predicates here are defined to run goals concurrently without having to deal with thread creation and maintenance explicitely.

Note that these predicates run goals concurrently and therefore these goals need to be thread-safe. As the predicates in this module also abort branches of the computation that are no longer needed, predicates that have side-effect must act properly. In a nutshell, this has the following consequences:

author
- Jan Wielemaker */
 concurrent(+N, :Goals, Options) is semidet
Run Goals in parallel using N threads. This call blocks until all work has been done. The Goals must be independent. They should not communicate using shared variables or any form of global data. All Goals must be thread-safe.

Execution succeeds if all goals have succeeded. If one goal fails or throws an exception, other workers are abandoned as soon as possible and the entire computation fails or re-throws the exception. Note that if multiple goals fail or raise an error it is not defined which error or failure is reported.

On successful completion, variable bindings are returned. Note however that threads have independent stacks and therefore the goal is copied to the worker thread and the result is copied back to the caller of concurrent/3.

Choosing the right number of threads is not always obvious. Here are some scenarios:

Arguments:
N- Number of worker-threads to create. Using 1, no threads are created. If N is larger than the number of Goals we create exactly as many threads as there are Goals.
Goals- List of callable terms.
Options- Passed to thread_create/3 for creating the workers. Only options changing the stack-sizes can be used. In particular, do not pass the detached or alias options.
See also
- In many cases, concurrent_maplist/2 and friends is easier to program and is tractable to program analysis.
  150concurrent(1, M:List, _) :-
  151    !,
  152    maplist(once_in_module(M), List).
  153concurrent(N, M:List, Options) :-
  154    must_be(positive_integer, N),
  155    must_be(list(callable), List),
  156    length(List, JobCount),
  157    message_queue_create(Done),
  158    message_queue_create(Queue),
  159    WorkerCount is min(N, JobCount),
  160    create_workers(WorkerCount, Queue, Done, Workers, Options),
  161    submit_goals(List, 1, M, Queue, VarList),
  162    forall(between(1, WorkerCount, _),
  163           thread_send_message(Queue, done)),
  164    VT =.. [vars|VarList],
  165    concur_wait(JobCount, Done, VT, cleanup(Workers, Queue),
  166                Result, [], Exitted),
  167    subtract(Workers, Exitted, RemainingWorkers),
  168    concur_cleanup(Result, RemainingWorkers, [Queue, Done]),
  169    (   Result == true
  170    ->  true
  171    ;   Result = false
  172    ->  fail
  173    ;   Result = exception(Error)
  174    ->  throw(Error)
  175    ).
  176
  177once_in_module(M, Goal) :-
  178    call(M:Goal), !.
 submit_goals(+List, +Id0, +Module, +Queue, -Vars) is det
Send all jobs from List to Queue. Each goal is added to Queue as a term goal(Id, Goal, Vars). Vars is unified with a list of lists of free variables appearing in each goal.
  186submit_goals([], _, _, _, []).
  187submit_goals([H|T], I, M, Queue, [Vars|VT]) :-
  188    term_variables(H, Vars),
  189    thread_send_message(Queue, goal(I, M:H, Vars)),
  190    I2 is I + 1,
  191    submit_goals(T, I2, M, Queue, VT).
 concur_wait(+N, +Done:queue, +VT:compound, +Cleanup, -Result, +Exitted0, -Exitted) is semidet
Wait for completion, failure or error.
Arguments:
Exited- List of thread-ids with threads that completed before all work was done.
  202concur_wait(0, _, _, _, true, Exited, Exited) :- !.
  203concur_wait(N, Done, VT, Cleanup, Status, Exitted0, Exitted) :-
  204    debug(concurrent, 'Concurrent: waiting for workers ...', []),
  205    catch(thread_get_message(Done, Exit), Error,
  206          concur_abort(Error, Cleanup, Done, Exitted0)),
  207    debug(concurrent, 'Waiting: received ~p', [Exit]),
  208    (   Exit = done(Id, Vars)
  209    ->  debug(concurrent, 'Concurrent: Job ~p completed with ~p', [Id, Vars]),
  210        arg(Id, VT, Vars),
  211        N2 is N - 1,
  212        concur_wait(N2, Done, VT, Cleanup, Status, Exitted0, Exitted)
  213    ;   Exit = finished(Thread)
  214    ->  thread_join(Thread, JoinStatus),
  215        debug(concurrent, 'Concurrent: waiter ~p joined: ~p',
  216              [Thread, JoinStatus]),
  217        (   JoinStatus == true
  218        ->  concur_wait(N, Done, VT, Cleanup, Status, [Thread|Exitted0], Exitted)
  219        ;   Status = JoinStatus,
  220            Exitted = [Thread|Exitted0]
  221        )
  222    ).
  223
  224concur_abort(Error, cleanup(Workers, Queue), Done, Exitted) :-
  225    debug(concurrent, 'Concurrent: got ~p', [Error]),
  226    subtract(Workers, Exitted, RemainingWorkers),
  227    concur_cleanup(Error, RemainingWorkers, [Queue, Done]),
  228    throw(Error).
  229
  230create_workers(N, Queue, Done, [Id|Ids], Options) :-
  231    N > 0,
  232    !,
  233    thread_create(worker(Queue, Done), Id,
  234                  [ at_exit(thread_send_message(Done, finished(Id)))
  235                  | Options
  236                  ]),
  237    N2 is N - 1,
  238    create_workers(N2, Queue, Done, Ids, Options).
  239create_workers(_, _, _, [], _).
 worker(+WorkQueue, +DoneQueue) is det
Process jobs from WorkQueue and send the results to DoneQueue.
  246worker(Queue, Done) :-
  247    thread_get_message(Queue, Message),
  248    debug(concurrent, 'Worker: received ~p', [Message]),
  249    (   Message = goal(Id, Goal, Vars)
  250    ->  (   Goal
  251        ->  thread_send_message(Done, done(Id, Vars)),
  252            worker(Queue, Done)
  253        )
  254    ;   true
  255    ).
 concur_cleanup(+Result, +Workers:list, +Queues:list) is det
Cleanup the concurrent workers and message queues. If Result is not true, signal all workers to make them stop prematurely. If result is true we assume all workers have been instructed to stop or have stopped themselves.
  265concur_cleanup(Result, Workers, Queues) :-
  266    !,
  267    (   Result == true
  268    ->  true
  269    ;   kill_workers(Workers)
  270    ),
  271    join_all(Workers),
  272    maplist(message_queue_destroy, Queues).
  273
  274kill_workers([]).
  275kill_workers([Id|T]) :-
  276    debug(concurrent, 'Signalling ~w', [Id]),
  277    catch(thread_signal(Id, abort), _, true),
  278    kill_workers(T).
  279
  280join_all([]).
  281join_all([Id|T]) :-
  282    thread_join(Id, _),
  283    join_all(T).
  284
  285
  286                 /*******************************
  287                 *             MAPLIST          *
  288                 *******************************/
 concurrent_maplist(:Goal, +List) is semidet
 concurrent_maplist(:Goal, +List1, +List2) is semidet
 concurrent_maplist(:Goal, +List1, +List2, +List3) is semidet
Concurrent version of maplist/2. This predicate uses concurrent/3, using multiple worker threads. The number of threads is the minimum of the list length and the number of cores available. The number of cores is determined using the prolog flag cpu_count. If this flag is absent or 1 or List has less than two elements, this predicate calls the corresponding maplist/N version using a wrapper based on once/1. Note that all goals are executed as if wrapped in once/1 and therefore these predicates are semidet.

Note that the the overhead of this predicate is considerable and therefore Goal must be fairly expensive before one reaches a speedup.

  307concurrent_maplist(Goal, List) :-
  308    workers(List, WorkerCount),
  309    !,
  310    maplist(ml_goal(Goal), List, Goals),
  311    concurrent(WorkerCount, Goals, []).
  312concurrent_maplist(M:Goal, List) :-
  313    maplist(once_in_module(M, Goal), List).
  314
  315once_in_module(M, Goal, Arg) :-
  316    call(M:Goal, Arg), !.
  317
  318ml_goal(Goal, Elem, call(Goal, Elem)).
  319
  320concurrent_maplist(Goal, List1, List2) :-
  321    same_length(List1, List2),
  322    workers(List1, WorkerCount),
  323    !,
  324    maplist(ml_goal(Goal), List1, List2, Goals),
  325    concurrent(WorkerCount, Goals, []).
  326concurrent_maplist(M:Goal, List1, List2) :-
  327    maplist(once_in_module(M, Goal), List1, List2).
  328
  329once_in_module(M, Goal, Arg1, Arg2) :-
  330    call(M:Goal, Arg1, Arg2), !.
  331
  332ml_goal(Goal, Elem1, Elem2, call(Goal, Elem1, Elem2)).
  333
  334concurrent_maplist(Goal, List1, List2, List3) :-
  335    same_length(List1, List2, List3),
  336    workers(List1, WorkerCount),
  337    !,
  338    maplist(ml_goal(Goal), List1, List2, List3, Goals),
  339    concurrent(WorkerCount, Goals, []).
  340concurrent_maplist(M:Goal, List1, List2, List3) :-
  341    maplist(once_in_module(M, Goal), List1, List2, List3).
  342
  343once_in_module(M, Goal, Arg1, Arg2, Arg3) :-
  344    call(M:Goal, Arg1, Arg2, Arg3), !.
  345
  346ml_goal(Goal, Elem1, Elem2, Elem3, call(Goal, Elem1, Elem2, Elem3)).
  347
  348workers(List, Count) :-
  349    current_prolog_flag(cpu_count, Cores),
  350    Cores > 1,
  351    length(List, Len),
  352    Count is min(Cores,Len),
  353    Count > 1,
  354    !.
  355
  356same_length([], [], []).
  357same_length([_|T1], [_|T2], [_|T3]) :-
  358    same_length(T1, T2, T3).
  359
  360
  361                 /*******************************
  362                 *             FIRST            *
  363                 *******************************/
 first_solution(-X, :Goals, +Options) is semidet
Try alternative solvers concurrently, returning the first answer. In a typical scenario, solving any of the goals in Goals is satisfactory for the application to continue. As soon as one of the tried alternatives is successful, all the others are killed and first_solution/3 succeeds.

For example, if it is unclear whether it is better to search a graph breadth-first or depth-first we can use:

search_graph(Grap, Path) :-
         first_solution(Path, [ breadth_first(Graph, Path),
                                depth_first(Graph, Path)
                              ],
                        []).

Options include thread stack-sizes passed to thread_create, as well as the options on_fail and on_error that specify what to do if a solver fails or triggers an error. By default execution of all solvers is terminated and the result is returned. Sometimes one may wish to continue. One such scenario is if one of the solvers may run out of resources or one of the solvers is known to be incomplete.

on_fail(Action)
If stop (default), terminate all threads and stop with the failure. If continue, keep waiting.
on_error(Action)
As above, re-throwing the error if an error appears.
bug
- first_solution/3 cannot deal with non-determinism. There is no obvious way to fit non-determinism into it. If multiple solutions are needed wrap the solvers in findall/3.
  403first_solution(X, M:List, Options) :-
  404    message_queue_create(Done),
  405    thread_options(Options, ThreadOptions, RestOptions),
  406    length(List, JobCount),
  407    create_solvers(List, M, X, Done, Solvers, ThreadOptions),
  408    wait_for_one(JobCount, Done, Result, RestOptions),
  409    concur_cleanup(kill, Solvers, [Done]),
  410    (   Result = done(_, Var)
  411    ->  X = Var
  412    ;   Result = error(_, Error)
  413    ->  throw(Error)
  414    ).
  415
  416create_solvers([], _, _, _, [], _).
  417create_solvers([H|T], M, X, Done, [Id|IDs], Options) :-
  418    thread_create(solve(M:H, X, Done), Id, Options),
  419    create_solvers(T, M, X, Done, IDs, Options).
  420
  421solve(Goal, Var, Queue) :-
  422    thread_self(Me),
  423    (   catch(Goal, E, true)
  424    ->  (   var(E)
  425        ->  thread_send_message(Queue, done(Me, Var))
  426        ;   thread_send_message(Queue, error(Me, E))
  427        )
  428    ;   thread_send_message(Queue, failed(Me))
  429    ).
  430
  431wait_for_one(0, _, failed, _) :- !.
  432wait_for_one(JobCount, Queue, Result, Options) :-
  433    thread_get_message(Queue, Msg),
  434    LeftCount is JobCount - 1,
  435    (   Msg = done(_, _)
  436    ->  Result = Msg
  437    ;   Msg = failed(_)
  438    ->  (   option(on_fail(stop), Options, stop)
  439        ->  Result = Msg
  440        ;   wait_for_one(LeftCount, Queue, Result, Options)
  441        )
  442    ;   Msg = error(_, _)
  443    ->  (   option(on_error(stop), Options, stop)
  444        ->  Result = Msg
  445        ;   wait_for_one(LeftCount, Queue, Result, Options)
  446        )
  447    ).
 thread_options(+Options, -ThreadOptions, -RestOptions) is det
Split the option list over thread(-size) options and other options.
  455thread_options([], [], []).
  456thread_options([H|T], [H|Th], O) :-
  457    thread_option(H),
  458    !,
  459    thread_options(T, Th, O).
  460thread_options([H|T], Th, [H|O]) :-
  461    thread_options(T, Th, O).
  462
  463thread_option(local(_)).
  464thread_option(global(_)).
  465thread_option(trail(_)).
  466thread_option(argument(_)).
  467thread_option(stack(_)).
 call_in_thread(+Thread, :Goal) is semidet
Run Goal as an interrupt in the context of Thread. This is based on thread_signal/2. If waiting times out, we inject a stop(Reason) exception into Goal. Interrupts can be nested, i.e., it is allowed to run a call_in_thread/2 while the target thread is processing such an interrupt.

This predicate is primarily intended for debugging and inspection tasks.

  481call_in_thread(Thread, Goal) :-
  482    thread_self(Thread),
  483    !,
  484    once(Goal).
  485call_in_thread(Thread, Goal) :-
  486    term_variables(Goal, Vars),
  487    thread_self(Me),
  488    A is random(1 000 000 000),
  489    thread_signal(Thread, run_in_thread(Goal,Vars,A,Me)),
  490    catch(thread_get_message(in_thread(A,Result)),
  491          Error,
  492          forward_exception(Thread, A, Error)),
  493    (   Result = true(Vars)
  494    ->  true
  495    ;   Result = error(Error)
  496    ->  throw(Error)
  497    ;   fail
  498    ).
  499
  500run_in_thread(Goal, Vars, Id, Sender) :-
  501    (   catch_with_backtrace(call(Goal), Error, true)
  502    ->  (   var(Error)
  503        ->  thread_send_message(Sender, in_thread(Id, true(Vars)))
  504        ;   Error = stop(_)
  505        ->  true
  506        ;   thread_send_message(Sender, in_thread(Id, error(Error)))
  507        )
  508    ;   thread_send_message(Sender, in_thread(Id, false))
  509    ).
  510
  511forward_exception(Thread, Id, Error) :-
  512    kill_with(Error, Kill),
  513    thread_signal(Thread, kill_task(Id, Kill)),
  514    throw(Error).
  515
  516kill_with(time_limit_exceeded, stop(time_limit_exceeded)) :-
  517    !.
  518kill_with(_, stop(interrupt)).
  519
  520kill_task(Id, Exception) :-
  521    prolog_current_frame(Frame),
  522    prolog_frame_attribute(Frame, parent_goal,
  523                           run_in_thread(_Goal, _Vars, Id, _Sender)),
  524    !,
  525    throw(Exception).
  526kill_task(_, _)