Runtime¶
The INFINITY.JS runtime executes javascript files and provides a set of runtime library functions, mostly sorted into modules, as well as a couple of variables. Since it supports multithreading, there may be more than one script running at the same time. Each of these scripts has its own runtime environment and some of the runtime functions and global variables are used to synchronize and control multithreaded execution.
All of the runtime functions and variables are organized within the infinity namespace, with one exception: the console namespace of the runtime supports the usual output functions that you are probably used to from browser environments or other javascript runtimes (e.g. console.log()). Apart from that, everything else can be found within the infinity namespace.
Variables¶
There's a couple of variables inside the infinity namespace that you should be aware about:
-
infinity.terminatedThis will always befalseunless the current script should terminate itself. Scripts won't be forcefully terminated - instead this runtime variable will switch totrueto signal the current script, that it should terminate itself. For your main program this might happen by the user pressingctrl+cto abort the program, or by the operating system sending the INFINITY.JS process a signal to terminate. If you are writing a server application or a program that might run for a longer time, then make sure that you regularly check the value ofinfinity.terminatedto ensure that your program reacts (and terminates) when requested to do so.Inside a thread,
infinity.terminatedreflects the termination flag of the main program. -
infinity.threadTerminatedOnly available in scripts that run as threads (see infinity.thread). It switches totruewhen the main program calls the thread'sstop()method. Threads should check bothinfinity.terminatedandinfinity.threadTerminatedin their loops. -
infinity.current.rootThe path of the folder containing the main program file (usually yourmain.js). -
infinity.current.runThe path of the folder containing the INFINITY.JS executable (e.g.bin/win-x64/). -
infinity.current.tempThe path of INFINITY.JS'stempfolder (../temprelative to the executable). The folder is created on startup and its content is deleted on startup and on exit. -
infinity.current.dir,infinity.current.fileThe folder and the file name of the script that is currently executed (e.g. an included file).
There are a couple more variables that are described in the api reference, e.g. the infinity namespace and the infinity.current namespace.
Functions¶
You can find a complete list and description of the runtime functions in the API reference, but here are some that you might find useful:
-
infinity.terminate( exitCode? )This will set theinfinity.terminatedvariable of the main program (and therefore of all threads) totrue, no matter if you call the function from the main program or a thread. So, calling this function anywhere in your application will ask your main program to terminate. The optionalexitCodeis returned by the INFINITY.JS process, e.g. to let systemd restart a service withRestart=on-failure. -
infinity.getGlobal( name )Returns the value of a global variable (or namespace) by its name. Since there is no globalwindowobject like in web browser environments, you can use this function to get global variables by their name. Of course you can just write them normally likelet root = infinity.current.root;, but if you want to use a variable name, you might need this function. -
infinity.sleep( milliseconds );Waits for the given number of milliseconds without causing cpu load. When writing a script that should run in a thread and that just has to do work sporadically (like monitoring some resource or performing cleanup operations), then you should use the sleep function while waiting to reduce cpu load.Make sure your script doesn't oversleep changes in the
infinity.terminatedvariable, though. Even if your script only has to perform some work every minute, you should only sleep for half a second, or a second at a time and always check theinfinity.terminatedvalue in between, to ensure that your thread (or main program) terminates properly when requested to do so.
Multi-threading Architecture¶
INFINITY.JS supports true multi-threading where multiple JavaScript files can execute in parallel. Each thread has its own isolated JavaScript runtime environment with separate memory space, but threads can communicate through the event system and shared memory.
Thread Architecture Diagram¶
graph TB
subgraph "Main Program"
MainRuntime["Main Runtime<br/>main.js"]
MainVars["infinity.terminated<br/>infinity.current.*"]
Thread1Obj["thread1 = new infinity.thread()"]
Thread2Obj["thread2 = new infinity.thread()"]
end
subgraph "Worker Thread 1"
Thread1Runtime["Thread Runtime<br/>worker1.js"]
Thread1Vars["infinity.threadTerminated<br/>infinity.current.*"]
Thread1Work["Thread Processing Loop"]
end
subgraph "Worker Thread 2"
Thread2Runtime["Thread Runtime<br/>worker2.js"]
Thread2Vars["infinity.threadTerminated<br/>infinity.current.*"]
Thread2Work["Thread Processing Loop"]
end
subgraph "Shared Resources"
EventQueue["Event Queue<br/>infinity.event"]
SharedMem["Shared Memory<br/>infinity.memory"]
Database["Database Connections<br/>infinity.database"]
end
MainRuntime -->|"start()"| Thread1Runtime
MainRuntime -->|"start()"| Thread2Runtime
MainRuntime -->|"stop()"| Thread1Vars
MainRuntime -->|"stop()"| Thread2Vars
Thread1Runtime --> Thread1Work
Thread2Runtime --> Thread2Work
Thread1Work -->|"checks"| Thread1Vars
Thread2Work -->|"checks"| Thread2Vars
MainRuntime <-->|"send/register"| EventQueue
Thread1Runtime <-->|"send/register"| EventQueue
Thread2Runtime <-->|"send/register"| EventQueue
MainRuntime <-->|"read/write"| SharedMem
Thread1Runtime <-->|"read/write"| SharedMem
Thread2Runtime <-->|"read/write"| SharedMem
MainRuntime --> Database
Thread1Runtime --> Database
Thread2Runtime --> Database
style MainRuntime fill:#4a90e2
style Thread1Runtime fill:#7cb342
style Thread2Runtime fill:#7cb342
style EventQueue fill:#ffa726
style SharedMem fill:#ffa726
style Database fill:#ffa726 Thread Lifecycle¶
Threads in INFINITY.JS follow a simple lifecycle:
- Creation:
let thread = new infinity.thread('script.js', priority, onTerminated)- the script path is relative to the main program folder - Start:
thread.start()- Begins parallel execution - Execution: Thread runs its JavaScript file independently
- Termination:
thread.stop()- Setsinfinity.threadTerminated = truein the thread and waits until the thread script has finished - Cleanup: Thread checks
infinity.threadTerminatedand exits gracefully
A thread also ends when its script reaches the end. The thread object's terminated property tells the main program whether the thread has finished. The optional onTerminated callback receives the thread's result (set in the thread with infinity.thread.result = ...) and an error message; it is executed in the main thread, e.g. while the main program calls infinity.processEvents().
Thread Priorities¶
Threads can be created with different priorities to control CPU allocation (thread priorities are currently only applied under Windows):
infinity.thread.priority.idle // Lowest priority
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 // Highest priority
Thread Communication¶
Threads communicate through: - Event System (infinity.event) - Message passing with callbacks - Shared Memory (infinity.memory) - Direct data sharing - Database (infinity.database) - Persistent shared state
Example thread pattern:
// main.js
infinity.loadModule('infinity.thread');
let worker = new infinity.thread('worker.js', infinity.thread.priority.normal);
worker.start();
while (!infinity.terminated) {
infinity.event.processQueue();
infinity.sleep(25);
}
// Ask the thread to terminate and wait until it has finished:
worker.stop();
// worker.js
while (!infinity.terminated && !infinity.threadTerminated) {
// Do work
infinity.event.processQueue();
infinity.sleep(100);
}
Event System Architecture¶
The event system provides asynchronous message passing between the main program and threads. Events are queued and processed when processQueue() is called, allowing for loose coupling between components.
Event System Diagram¶
sequenceDiagram
participant Main as Main Program
participant Queue as Event Queue
participant T1 as Thread 1
participant T2 as Thread 2
Note over Main,T2: Registration Phase
Main->>Queue: register('userAdded', callback1)
T1->>Queue: register('userAdded', callback2)
T2->>Queue: register('dataReady', callback3)
Note over Main,T2: Event Sending Phase
T2->>Queue: send('userAdded', {id: 123})
Note over Queue: Event queued<br/>Not processed yet
Main->>Queue: send('dataReady', {data: [...]})
Note over Queue: Event queued
Note over Main,T2: Processing Phase
Main->>Queue: processQueue()
Queue->>Main: callback1({id: 123})
Note over Main: Event handler<br/>executes
T1->>Queue: processQueue()
Queue->>T1: callback2({id: 123})
Note over T1: Event handler<br/>executes
T2->>Queue: processQueue()
Queue->>T2: callback3({data: [...]})
Note over T2: Event handler<br/>executes Event Flow Diagram¶
graph LR
subgraph "Any Thread/Main"
Send["infinity.event.send()<br/>'eventName', params"]
end
subgraph "Event Queue"
Queue["Queued Events<br/>(Thread-Safe)"]
end
subgraph "Receiving Thread/Main"
Process["infinity.event.processQueue()"]
Handlers["Registered Handlers<br/>callbacks"]
Execute["Execute Callback<br/>with params"]
end
Send -->|"Enqueue"| Queue
Queue -->|"Dequeue"| Process
Process --> Handlers
Handlers --> Execute
style Send fill:#4a90e2
style Queue fill:#ffa726
style Process fill:#7cb342
style Handlers fill:#7cb342
style Execute fill:#7cb342 Event System Features¶
Key Characteristics: - Asynchronous: Events are queued, not executed immediately - Thread-Safe: Multiple threads can send events concurrently - Decoupled: Senders don't need to know about receivers - Flexible: Any JSON-serializable data can be passed as parameters
Usage Pattern:
// Register event handler (in any thread or main program)
infinity.event.register('taskComplete', function(params: any): void {
console.log('Task completed: ' + params.taskId);
// Process the event
});
// Send event (from any thread or main program)
infinity.event.send('taskComplete', { taskId: 42, result: 'success' });
// Process queued events (must be called regularly)
while (!infinity.terminated) {
infinity.event.processQueue(); // Executes callbacks for queued events
infinity.sleep(25);
}
Important Notes: - Events are only processed when processQueue() is called - Each thread must call processQueue() to receive its events - Event handlers execute synchronously during processQueue() - Events sent between threads are copied (as JSON), not shared by reference - Each script can register only one handler per event name; call infinity.event.unregister() before registering a new one
Now that you know some of the useful global runtime features, we'll show you how to split your source code into multiple files by using INFINITY.JS's include mechanism: Includes
Resources and Memory¶
Some of the objects that you instantiate in your code will actually access resources allocated by the INFINITY.JS runtime. These will automatically be released again when the object is destroyed by the javascript garbage collector, so you don't have to deal with that.
However, when allocating resources that you'd like to free early (e.g. when creating a gigabyte-sized memory stream), you have the option of releasing these resources explicitly. All objects of the INFINITY.JS runtime that have a method called free() can be released immediately by calling that free() method. This will release the underlying system resources (e.g. memory) used by the object. Make sure that you don't reuse the object after calling free() on it, as this will cause a memory access violation, because the object will be accessing system resources that have already been deallocated.
The best way to ensure that you are releasing an object that has a free() method is by using a try-finally block like this:
infinity.loadModule( 'infinity.database' );
let database = new infinity.database();
try {
// use the database object
} finally {
database.free();
}
But, as noted in the beginning: all of this is purely optional and just an added option to give you more control over allocating and deallocating memory or system resources. If you don't call the free() method, then the INFINITY.JS runtime will free the resources later through the automatic garbage collector.