Routzie - documentation

Using Threads in Your Machine

Your machine supports multiple threads, each running as a real server-side thread. The number of threads available depends on your plan, but you can utilize several threads within a single machine.

Each thread has its own context, and you can communicate between threads using promises.

Starting a Thread

To start a thread, use the startThread function and provide the path to the file containing your thread code. This file must export at least one function, which will be called when the thread starts. You can export additional functions and invoke them from other threads as needed.

Disposing a Thread

To dispose of a thread, call the dispose function on the ThreadRef object. This will immediately stop the thread.

Example

Here is a simple example of setting up a thread and calling a function within it:

Main file (index.js):

let threadRef: ThreadRef bootstrap(async () => { threadRef = await startThread('./thread.js') const result = await threadRef.threadFunction('Hello world') console.log(result) })

Thread file (thread.js):

async function threadFunction(data) { return `Thread says: ${data}` } exposeCallables({ threadFunction, })

Communication from thread to host:

You can call functions from host in thread, but you need to use host object for that. This object is available only in thread, and it has exposeCallables function, which you can use to expose functions to host. All functions must be promisified, and you can not use any global objects in them.

Example:

Main file (index.js):

exposeCallables({ hostFunction: async (data) => { console.log('Host says:', data) }, })

Thread file (thread.js):

console.log(await host.hostFunction('Hello from thread'))

Notes:

  • You can not use any global objects in thread, all dependencies must be passed via function arguments.
  • You can not use any global objects in functions exposed to host.
  • Overall usage statistics and watchdogs are tracked together, if your thread freezes, your machine will be restarted.
  • Memory is separated, and thread always allocates it's own heap, but it is limited by your plan - usualy 16MB.
  • Sharing of data can be done only via function arguments and return values, you can always use Uint8Array to pass binary data.
  • Some of functions are not available in threads, like router, blobs (including media manipulation server).

© 2025 Routzie Routzie.com