1/*  Part of Extended Libraries for Prolog
    2
    3    Author:        Edison Mera Menendez
    4    E-mail:        efmera@gmail.com
    5    WWW:           https://github.com/edisonm/xlibrary
    6    Copyright (C): 2020, Process Design Center, Breda, The Netherlands.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(concurrent_forall,
   36          [ concurrent_forall/2,
   37            concurrent_forall/3
   38          ]).   39
   40:- use_module(countsols).   41:- use_module(library(thread), []).   42:- use_module(library(ordsets)).   43:- use_module(library(debug)).   44:- use_module(library(lists)).   45
   46:- meta_predicate
   47        handle_result(+, 0 ),
   48        concurrent_forall(0, 0 ),
   49        concurrent_forall(0, 0, 0 ).
 concurrent_forall(:Cond, :Action) is semidet
Concurrent version of forall/2. This predicate will prove several alternatives of Cond with Action, using multiple threads. The maximum number of threads defined is the amount of cores available. If the number of pending jobs is greater than the number of workers, then the system will wait until a job is finished before to process the next alternative, this is done to avoid that the alternatives of Cond could overflow the memory.
   60concurrent_forall(Cond, Action) :-
   61    concurrent_forall(Cond, Action, true).
 concurrent_forall(:Cond, :Action, :Join) is semidet
Join is called after the execution of Action in the main thread. Sometimes we still need to execute a part of the code serialized. Is equivalent to forall(Cond, (Action, ignore(Join))).
   69concurrent_forall(Cond, Action, Join) :-
   70    current_prolog_flag(cpu_count, CPUCount),
   71    message_queue_create(Done),
   72    message_queue_create(Queue),
   73    ini_counter(0, Counter),
   74    SWorkers = workers(0, []),
   75    term_variables(Join, JoinVars), sort(JoinVars, OJoinVars),
   76    term_variables(Cond, CondVars), sort(CondVars, OCondVars),
   77    ord_subtract(OJoinVars, OCondVars, ExternVars),
   78    Templ =.. [v|JoinVars],
   79    copy_term(t(Join, Templ, ExternVars), t(Join2, Templ2, ExternVars)),
   80    forall(Cond,
   81           (   SWorkers = workers(WorkerCount, Workers),
   82               Counter = count(I1),
   83               concur(done(WorkerCount), I1, I2, Join2, Templ2, Done, cleanup(Workers, Queue), Result, [], Exitted),
   84               nb_setarg(1, Counter, I2),
   85               handle_result(Result,
   86                             ( subtract(Workers, Exitted, RemainingWorkers),
   87                               forall(member(_, RemainingWorkers),
   88                                      thread_send_message(Queue, done)),
   89                               thread:concur_cleanup(Result, RemainingWorkers, [Queue, Done])
   90                             )),
   91               inc_counter(Counter, I),
   92               (   WorkerCount < CPUCount
   93               ->  create_worker(Queue, Done, Id, []),
   94                   succ(WorkerCount, WorkerCount2),
   95                   nb_setarg(1, SWorkers, WorkerCount2),
   96                   nb_setarg(2, SWorkers, [Id|Workers])
   97               ;   true
   98               ),
   99               thread_send_message(Queue, goal(I, Action, Templ))
  100           )),
  101    SWorkers = workers(WorkerCount, Workers),
  102    forall(member(_, Workers),
  103           thread_send_message(Queue, done)),
  104    Counter = count(I),
  105    concur(wait, I, _, Join2, Templ2, Done, cleanup(Workers, Queue), Result, [], Exitted),
  106    subtract(Workers, Exitted, RemainingWorkers),
  107    thread:concur_cleanup(Result, RemainingWorkers, [Queue, Done]),
  108    handle_result(Result, true).
  109
  110handle_result(Result, FailHandler) :-
  111    (   Result == true
  112    ->  true
  113    ;   Result = false
  114    ->  FailHandler,
  115        fail
  116    ;   Result = exception(Error)
  117    ->  throw(Error)
  118    ).
  119
  120create_worker(Queue, Done, Id, Options) :-
  121    thread_create(worker(Queue, Done), Id,
  122                  [ at_exit(thread_send_message(Done, finished(Id)))
  123                  | Options
  124                  ]).
 worker(+WorkQueue, +DoneQueue) is det
Process jobs from WorkQueue and send the results to DoneQueue.
  130worker(Queue, Done) :-
  131    thread_get_message(Queue, Message),
  132    debug(concurrent, 'Worker: received ~p', [Message]),
  133    (   Message = goal(Id, Goal, Vars)
  134    ->  (   Goal
  135        ->  thread_send_message(Done, done(Id, Vars)),
  136            worker(Queue, Done)
  137        )
  138    ;   true
  139    ).
 concur(+Wait, +N1, -N, :Join, +Vars, +Done:queue, +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.
  149concur(done(NW), N, N, _, _, Done, _, true, Exitted, Exitted) :-
  150    message_queue_property(Done, size(0 )),
  151    N =< NW,
  152    !.
  153concur(wait, 0,  0, _, _, _, _, true, Exitted, Exitted) :- !.
  154concur(Wait, N1, N, Join, Vars, Done, Cleanup, Status, Exitted1, Exitted) :-
  155    debug(concurrent, 'Concurrent: waiting for workers ...', []),
  156    catch(thread_get_message(Done, Exit), Error,
  157          thread:concur_abort(Error, Cleanup, Done, Exitted1)),
  158    debug(concurrent, 'Waiting: received ~p', [Exit]),
  159    (   Exit = done(Id, Bind)
  160    ->  debug(concurrent, 'Concurrent: Job ~p completed', [Id]),
  161        ignore(\+ ( Vars = Bind,
  162                    Join
  163                  )),
  164        N2 is N1 - 1,
  165        concur(Wait, N2, N, Join, Vars, Done, Cleanup, Status, Exitted1, Exitted)
  166    ;   Exit = finished(Thread)
  167    ->  thread_join(Thread, JoinStatus),
  168        debug(concurrent, 'Concurrent: waiter ~p joined: ~p',
  169              [Thread, JoinStatus]),
  170        (   JoinStatus == true
  171        ->  concur(Wait, N1, N, Join, Vars, Done, Cleanup, Status, [Thread|Exitted1], Exitted)
  172        ;   Status = JoinStatus,
  173            Exitted = [Thread|Exitted1]
  174        )
  175    )