Skip to main content
On this page

Multithreading

Encodexx allows you to conveniently work with SharedArrayBuffer and Atomics to create multithreaded applications. Below is a basic example of creating a task queue.

Describe the schema for the task:

schema.js
import { Serializer, t } from "encodexx";
export const TaskSchema = new Serializer([
{
id: t.str,
name: t.str,
createdAt: t.optional(t.date),
payload: t.optional(t.str),
},
]);

Next, we use SharedArrayBuffer and Atomics to create a task queue:

Run the code:

bash
node main.js
Worker 1 took the task Task 1 to process
Worker 2 took the task Task 2 to process
Worker 2 finished the task Task 2
Worker 2 took the task Task 3 to process
Worker 1 finished the task Task 1
Worker 1 took the task Task 4 to process
Worker 2 finished the task Task 3
Worker 2 took the task Task 5 to process
Worker 1 finished the task Task 4
Worker 1 - no more tasks
Worker 2 finished the task Task 5
Worker 2 - no more tasks