1.0.0 • Published 10 months ago

@esfx/threading-autoresetevent v1.0.0

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

@esfx/threading-autoresetevent

Provides AutoResetEvent, a threading primitive for use with Workers.

Overview

Installation

npm i @esfx/threading-autoresetevent

Usage

import { Worker, isMainThread, parentPort, workerData } from "worker_threads";
import { createInterface } from "readline";
import { AutoResetEvent } from "@esfx/threading-autoresetevent";

function worker_thread() {
    const workerReadyEvent = new AutoResetEvent(workerData[0]);
    const continueEvent = new AutoResetEvent(workerData[1]);

    // signal the main thread we are ready
    workerReadyEvent.set();

    let count = 0;
    while (true) {
        // wait for the main thread to set 'continueEvent'
        continueEvent.wait();
        parentPort.postMessage(`counter=${count++}`);
    }
}

function main() {
    // create two AutoResetEvents in the main thread
    const workerReadyEvent = new AutoResetEvent();
    const continueEvent = new AutoResetEvent();

    // create a Worker, passing the buffers of the two events
    const worker = new Worker(__filename, {
        workerData: [workerReadyEvent.buffer, continueEvent.buffer]
    });

    // wait for the worker to tell us it is ready
    workerReadyEvent.wait();

    console.log("worker is ready. Press ENTER to continue the worker...");
    worker.on("message", message => {
        console.log(`worker says: ${message}`);
    });

    const rl = createInterface({ input: process.stdin, output: process.stdout });
    rl.on("line", () => {
        // event is automatically reset as soon as a single waiter is signaled
        continueEvent.set();
    });
}

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.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