13.2.2 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 Prolog.Engine([name], [options])
- Create a new engine. The name argument names the engine. When
omitted, engines are named
engineN, where N is defined by a counter. The options argument provides additional configuration. Both arguments are optional.- Boolean
auto_close - When
true(defaultfalse, closing the last query associated with the engine also closes the engine.
- Boolean
- undefined close()
- Terminate the engine. This may be called safely multiple times on the same instance.
- Boolean Engine.call(Goal)
- Object query(...args)
- Object forEach(goal, ...args)
- Any with_frame(function, persist)
- Same as the corresponding methods on class Prolog, using the specified engine for running the Prolog goals.
- Any with(function)
- Run function using the specified Engine instance.