Did you know ... | Search Documentation: |
![]() | Using engines |
The WASM version of SWI-Prolog supports engines. The initial
engine is called main
. Additional engines can be used to
enumerate answers of multiple open queries as well as for implementing
coroutines. Combined with JavaScript async functions,
engines can provide cooperative multi-threading. For example,
to enumerate the answers of two queries we may use the following code
const e1 = new Prolog.Engine({auto_close:true}); const e2 = new Prolog.Engine({auto_close:true}); const q1 = e1.query(Query1); // see Prolog.query() const q2 = e2.query(Query2); try { for(;;) { const n1 = q1.next(); const n2 = q2.next(); if ( n1.done && n2.done ) break; // Handle answers } } finally { q1.close(); // also closes e1 q2.close(); } ...
Engines can also be used to create a cooperative thread. The example below creates a Prolog task that prints the numbers 1..20 to the console, one number every second.
... setTimeout(async () => { const e = new Prolog.Engine({auto_close:true}); await e.forEach("between(1,20,X),sleep(1)", (a) => console.out(a.X)); });
engine
N, where N
is defined by a counter. The options argument provides
additional configuration. Both arguments are optional.
auto_close
true
(default false
, closing the last
query associated with the engine also closes the engine.