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
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions src/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MessagePort } from 'worker_threads'

export interface StartupMessage {
tinypoolStartupMessage: true
filename: string | null
name: string
port: MessagePort
Expand Down
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
MessageChannel,
MessagePort,
receiveMessageOnPort,
parentPort,
} from 'worker_threads'
import { once } from 'events'
import EventEmitterAsyncResource from './EventEmitterAsyncResource'
Expand Down Expand Up @@ -688,6 +689,7 @@ class ThreadPool {
}

const message: StartupMessage = {
tinypoolStartupMessage: true,
filename: this.options.filename,
name: this.options.name,
port: port2,
Expand Down Expand Up @@ -1024,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()
}
Expand Down Expand Up @@ -1102,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'
Expand Down
1 change: 1 addition & 0 deletions src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ async function getHandler(
parentPort!.on('message', (message: StartupMessage) => {
useAtomics =
process.env.PISCINA_DISABLE_ATOMICS === '1' ? false : message.useAtomics
if (!message?.tinypoolStartupMessage) return
const { port, sharedBuffer, filename, name } = message
;(async function () {
if (filename !== null) {
Expand Down