-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
thread-worker.ts
52 lines (42 loc) · 1.24 KB
/
thread-worker.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { fileURLToPath } from 'url'
import { TransferListItem, Worker } from 'worker_threads'
import { TinypoolWorker } from '../common'
export default class ThreadWorker implements TinypoolWorker {
name = 'ThreadWorker'
runtime = 'worker_threads'
thread!: Worker
threadId!: number
initialize(options: Parameters<TinypoolWorker['initialize']>[0]) {
this.thread = new Worker(
fileURLToPath(import.meta.url + '/../entry/worker.js'),
options
)
this.threadId = this.thread.threadId
}
async terminate() {
return this.thread.terminate()
}
postMessage(message: any, transferListItem?: Readonly<TransferListItem[]>) {
return this.thread.postMessage(message, transferListItem)
}
on(event: string, callback: (...args: any[]) => void) {
return this.thread.on(event, callback)
}
once(event: string, callback: (...args: any[]) => void) {
return this.thread.once(event, callback)
}
emit(event: string, ...data: any[]) {
return this.thread.emit(event, ...data)
}
ref() {
return this.thread.ref()
}
unref() {
return this.thread.unref()
}
setChannel() {
throw new Error(
"{ runtime: 'worker_threads' } doesn't support channel. Use transferListItem instead."
)
}
}