Skip to content

infinity.thread

Module: infinity.thread

Classes:
Properties:
Interfaces:
Enums:

INFINITY.JS engine supports multithreading. You can create threads by using the infinity.thread namespace.


Classes

thread

Properties:

Methods:

Example:

infinity.loadModule('infinity.thread');

let thread = new infinity.thread('path/to/script.js');

thread.start();

// main program code

thread.stop();

This creates a thread that will execute a given javascript file in parallel to the main program. Each thread has its own javascript runtime. The start() method will start thread execution (running the script.js javascript file) and the thread.stop() method will signal the thread that it should stop and wait until it has finished. This will not interrupt the thread - it will only set the global infinity.threadTerminated variable in the thread's javascript runtime to true. This means that your thread will have to regularly check for that variable to determine, whether it should abort its execution:

// script.ts
while (!infinity.threadTerminated) {
    // do something
}

Of course, your thread may also terminate on its own when it finishes execution (e.g. some expensive calculation). Calling the stop() method on a thread that has already terminated won't cause any negative side effects.

Note: infinity.terminate() and the termination of the main program do not set infinity.threadTerminated. Inside the thread, infinity.terminated returns the value of the main program (since 3.11 also true after stop() of this thread), so a thread can check both values, or the main program has to call stop() on its threads before it finishes.

Note: The path to the script that you want to run in a thread has to be relative to the main program folder (and not to the file that creates the thread).

Note: You do not have to load the infinity.thread module inside your thread script. That module is only required to start threads and to access infinity.thread.result within the thread. All other modules used by the thread script have to be loaded inside the thread script.

A thread script can pass a result back to the main program by assigning it to infinity.thread.result. When the thread finishes, the optional onTerminated callback passed to the constructor is called with the result and, if the thread script failed, the error message:

// main.ts
infinity.loadModule('infinity.thread');

let finished = false;

let thread = new infinity.thread('calc.js', infinity.thread.priority.normal, function (result: any, error: string): void {
    if (error) {
        console.error('Thread failed: ' + error);
    } else {
        console.info('Thread result: ' + JSON.stringify(result));
    }
    finished = true;
});

thread.start();

while (!infinity.terminated && !finished) {
    infinity.processEvents(); // executes the onTerminated callback in the main thread
    infinity.sleep(100);
}

thread.stop();
// calc.ts
infinity.loadModule('infinity.thread');

infinity.thread.result = { sum: 1 + 2 };

Note: The onTerminated callback is executed in the runtime that created the thread object, when it calls infinity.processEvents() or stop() of this thread. Results may contain null values (since 3.11; before, they crashed the callback and a following stop() blocked forever).

You can change the thread's priority through the constructor's second argument:

infinity.loadModule('infinity.thread');
let thread = new infinity.thread('path/to/script.js', infinity.thread.priority.lower);

If you are creating a thread that only needs to perform periodically, then you might want to use the infinity.sleep() function inside the thread to yield execution and prevent high cpu load:

// script.ts
while (!infinity.threadTerminated) {
    // do something
    infinity.sleep(100); // sleep 100 milliseconds
}

Keep in mind that the thread won't be able to terminate itself while sleeping, so if you let it sleep for 2 seconds, then it will take up to 2 seconds to terminate the thread when your main program is terminated. So it's usually good practice to keep the sleep time reasonably low within threads, so that they don't linger too long before terminating.


Properties


terminated

Type: boolean

This value will be true if stop() has been called or the thread script has finished normally (it is the value the thread script sees as infinity.threadTerminated). Since 3.11 it is also true after the thread script ended with an error (it stayed false until stop() before).


Methods


constructor()

Creates a new thread. The script path needs to be relative to the main program folder (absolute paths are supported since 3.11). The thread can be started by calling the start() method, while the stop() method sets the thread runtime's infinity.threadTerminated variable to true indicating that the thread should terminate itself. Make sure that the scripts you run as threads check that variable, so that your program is able to terminate the threads properly when the main program terminates.

Signature:

constructor( scriptName: string, priority?: infinity.thread.priority, onTerminated?: infinity.thread.terminatedEvent )

Parameters:

  • scriptName: string

    Path to the script that should be run as a thread. The path needs to be relative to the main program folder.

  • priority: infinity.thread.priority, optional

    Thread priority, one of the following constants (only supported on Windows, ignored on other platforms):

    • infinity.thread.priority.idle
    • infinity.thread.priority.lowest
    • infinity.thread.priority.lower
    • infinity.thread.priority.normal (default)
    • infinity.thread.priority.high
    • infinity.thread.priority.higher
    • infinity.thread.priority.timeCritical
  • onTerminated: infinity.thread.terminatedEvent, optional

    Function that is called when the thread script has finished, by infinity.processEvents() or stop() of the runtime that created the thread (see the example above). null or undefined means no callback; any other non-function value throws a SyntaxError.

Example:

infinity.loadModule('infinity.thread');
let thread = new infinity.thread('services/worker.js', infinity.thread.priority.lower);

start()

Starts thread execution. A thread can only be started once.

Signature:

start(): void

Example:

infinity.loadModule('infinity.thread');
let thread = new infinity.thread('thread.js');
thread.start();

stop()

Notifies the thread that it should terminate itself, by setting the infinity.threadTerminated variable of the thread's javascript runtime to true, (since 3.11 also infinity.terminated of the thread script), and then waits until the thread has finished. A pending onTerminated callback of the thread is executed before stop() returns. You will need to make sure that the script you are running as a thread checks this variable and terminates itself. Otherwise stop() blocks forever and your main program won't be able to terminate properly when it is shut down. If the thread has not been started yet, it is started and then stopped.

Signature:

stop(): void

Example:

infinity.loadModule('infinity.thread');
let thread = new infinity.thread('thread.js');
thread.start();
infinity.sleep(500);
thread.stop();

Properties

result

Type: any

The result of the current thread. Assign a value to infinity.thread.result inside a thread script (which requires infinity.loadModule('infinity.thread') in the thread script) to pass it to the onTerminated callback of the thread object. The value is stored as a JSON copy, so it must be JSON-serializable. Reading it returns the value assigned before, or undefined. Accessing this property outside of a thread script throws an error.

Example:

// thread script
infinity.loadModule('infinity.thread');
infinity.thread.result = [1, 2, 3];

Interfaces

terminatedEvent

Signature:

(result: any, error: string): void

Callback function for the onTerminated parameter of the constructor. result is the value the thread script assigned to infinity.thread.result. error contains the error message if the thread script ended with an error. Values that have not been set are passed as undefined.


Enums

infinity.thread.priority

Thread priority. Lower priority will result in less system load. Thread priorities are only supported on Windows.

Values:

  • idle: 0
  • lowest: 1
  • lower: 2
  • normal: 3
  • high: 4
  • higher: 5
  • timeCritical: 6

Example:

infinity.loadModule('infinity.thread');
let priority = infinity.thread.priority.idle;