A.54 library(thread): High level thread primitives
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
      • The SWI-Prolog library
        • library(thread): High level thread primitives
          • concurrent/3
          • concurrent_forall/2
          • concurrent_forall/3
          • concurrent_and/2
          • concurrent_and/3
          • concurrent_maplist/2
          • concurrent_maplist/3
          • concurrent_maplist/4
          • first_solution/3
          • call_in_thread/2
    • Packages
Availability::- use_module(library(thread)).(can be autoloaded)
Source[semidet]concurrent(+N, :Goals, +Options)
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:

  • If the goals are CPU intensive and normally all succeeding, typically the number of CPUs is the optimal number of threads. Less does not use all CPUs, more wastes time in context switches and also uses more memory.
  • If the tasks are I/O bound the number of threads is typically higher than the number of CPUs.
  • If one or more of the goals may fail or produce an error, using a higher number of threads may find this earlier.
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.