-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05.multi-jump.js
38 lines (35 loc) · 1.02 KB
/
05.multi-jump.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { Worker, isMainThread, parentPort, workerData } from "worker_threads";
import RPCContext, { deferPromise } from "rpc-magic-proxy";
async function main() {
const ctx = new RPCContext();
const { promise, resolve } = deferPromise();
// First worker
ctx.bind(
new Worker(new URL(import.meta.url), {
workerData: await ctx.serialize({ resolve }),
}),
);
// Second worker
ctx.bind(
new Worker(new URL(import.meta.url), {
workerData: await ctx.serialize({ callback: await promise }),
}),
);
}
async function worker() {
const ctx = new RPCContext().bind(parentPort);
const { callback, resolve } = ctx.deserialize(workerData);
// First worker
if (resolve) {
const { promise, resolve: _resolve } = deferPromise();
await resolve(_resolve);
console.log("Worker 1 got:", await promise);
}
// Second worker
if (callback) {
await callback("Hello from worker 2");
}
// This will unbind listeners and allow worker to exit
ctx.reset();
}
isMainThread ? main() : worker();