Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: broadcast message to all workers #47

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
feat: broadcastMessage
Akryum committed Feb 17, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 82aa1142013b4eea97087ff0396a6c5b832234c0
15 changes: 15 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@ import {
MessageChannel,
MessagePort,
receiveMessageOnPort,
parentPort,
} from 'worker_threads'
import { once } from 'events'
import EventEmitterAsyncResource from './EventEmitterAsyncResource'
@@ -1025,6 +1026,12 @@ class Tinypool extends EventEmitterAsyncResource {
return this.#pool.runTask(task, { transferList, filename, name, signal })
}

broadcastMessage(message: any) {
for (const workerInfo of this.#pool.workers) {
workerInfo.worker.postMessage(message)
}
}

destroy() {
return this.#pool.destroy()
}
@@ -1103,6 +1110,14 @@ class Tinypool extends EventEmitterAsyncResource {
}
}

export function onBroadcastedMessage(handler: (message: any) => void) {
if (parentPort) {
parentPort.on('message', handler)
} else {
throw new Error('onBroadcastedMessage can only be used in worker threads')
}
}

const _workerId = process.__tinypool_state__?.workerId

export * from './common'