// SPDX-FileCopyrightText: 2024 Chris Duncan <chris@zoso.dev>
// SPDX-License-Identifier: GPL-3.0-or-later
+const Worker = globalThis.Worker
type Task = {
data: object,
.map(() => { return new Thread(this.#url) })
}
+ #assign (thread: Thread, task: Task) {
+ thread.isAvailable = false
+ thread.worker.onmessage = (event) => {
+ console.log('work done')
+ if (this.#tasks.length > 0) {
+ const next = this.#tasks.shift()
+ this.#assign(thread, next)
+ } else {
+ thread.isAvailable = true
+ }
+ task.resolve(event.data)
+ }
+ console.log('posting')
+ thread.worker.postMessage(task.data)
+ }
+
async work (data: object): Promise<any> {
return new Promise(resolve => {
const thread = this.#threads.find(t => t.isAvailable)
if (thread) {
- this.assign(thread, { data, resolve })
+ this.#assign(thread, { data, resolve })
} else {
this.#tasks.push({ data, resolve })
}
})
}
-
- assign (thread: Thread, task: Task) {
- thread.isAvailable = false
- thread.worker.addEventListener('message', (event) => {
- if (this.#tasks.length > 0) {
- const task = this.#tasks.shift()
- this.assign(thread, task.data)
- } else {
- thread.isAvailable = true
- }
- task.resolve(event.data)
- }, { once: true })
- thread.worker.postMessage(task.data)
- }
}