1.0.0 • Published 10 months ago

@esfx/threading-mutex v1.0.0

Weekly downloads
2
License
Apache-2.0
Repository
github
Last release
10 months ago

@esfx/threading-mutex

A Mutex class that performs locking across Worker instances using a SharedArrayBuffer.

Overview

Installation

npm i @esfx/threading-mutex

Usage

import { Worker, isMainThread, parentPort, workerData } from "worker_threads";
import { Mutex } from "@esfx/threading-mutex";
import { StructType, int32 } from "@esfx/struct-type";
import { sleep } from "@esfx/threading-sleep";

const SharedData = StructType([
    { name: "x", type: int32 },
    { name: "y", type: int32 },
]);

function worker_thread() {
    const m = new Mutex(workerData[0]);
    const data = new SharedData(workerData[1]);

    while (true) {
        sleep(250);

        m.lock();
        try {
            // inside of the lock we can mutate 'data' without
            // main() seeing a partial update.
            data.x++;
            data.y--;
        }
        finally {
            m.unlock();
        }
    }
}

function main() {
    const m = new Mutex();
    const data = new SharedData(/*shared*/ true);
    const worker = new Worker(__filename, { workerData: [m.buffer, data.buffer] });

    while (true) {
        sleep(500);

        m.lock();
        try {
            // inside of the lock, we know that we can safely read
            // both 'x' and 'y' and the worker will not modify
            // either value until we unlock.
            console.log(`x: ${data.x}, y: ${data.y}`);
        }
        finally {
            m.unlock();
        }
    }
}

if (isMainThread) {
    main();
}
else {
    worker_thread();
}

API

You can read more about the API here.

1.0.0

2 years ago

1.0.0-dev.7

2 years ago

1.0.0-pre.42

2 years ago

1.0.0-dev.8

2 years ago

1.0.0-pre.41

2 years ago

1.0.0-dev.5

2 years ago

1.0.0-pre.44

2 years ago

1.0.0-dev.6

2 years ago

1.0.0-pre.43

2 years ago

1.0.0-dev.4

2 years ago

1.0.0-dev.0

2 years ago

1.0.0-pre.40

2 years ago

1.0.0-pre.31

2 years ago

1.0.0-pre.33

2 years ago

1.0.0-pre.35

2 years ago

1.0.0-pre.34

2 years ago

1.0.0-pre.37

2 years ago

1.0.0-pre.36

2 years ago

1.0.0-pre.39

2 years ago

1.0.0-pre.38

2 years ago

1.0.0-pre.30

3 years ago

1.0.0-pre.26

3 years ago

1.0.0-pre.25

3 years ago

1.0.0-pre.28

3 years ago

1.0.0-pre.29

3 years ago

1.0.0-pre.23

3 years ago

1.0.0-pre.20

3 years ago

1.0.0-pre.19

3 years ago

1.0.0-pre.17

3 years ago

1.0.0-pre.16

3 years ago

1.0.0-pre.13

5 years ago

1.0.0-pre.12

5 years ago

1.0.0-pre.11

5 years ago

1.0.0-pre.9

5 years ago

1.0.0-pre.8

5 years ago